rethinkdb:获取从现在起两周内创建的具有唯一 ID 的行
rethinkdb: get rows created no later than two weeks from now with unique id
我有一个 table,其中一些行如下所示:
{
"id": "12345"
"created_date": Fri May 27 2016 22:06:25 GMT+00:00 ,
} {
"id": "6789"
"created_date": Mon May 30 2016 07:48:35 GMT+00:00 ,
}
etc...
我试图首先通过仅获取从今天起不迟于 2 周前创建的行来过滤行。
然后我试图通过仅获取唯一 ID(无重复)但仍然是最新的 ID 来进行过滤。
此过滤可以反向进行,如果这样效率更高的话。
与此伪代码类似的内容:
r.db().table().filter( r.time(r.row['created_date']) > r.now()-2_weeks).filter(latest-uniques-only)
这里有两个选项可以达到预期的效果。
使用过滤器和分组
您可以使用以下查询来执行此查找(代码使用 Javascript API 并通过数据资源管理器在 table 上进行了测试):
r.table('the_table')
.group('the_id') // group by the id
.filter((row) => {
return row('created_date').gt(r.now().sub(86400*14)); // only include records from the last 14 days
})
.orderBy(r.desc('created_date')) // order by latest first
.pluck('the_id', 'created_date') // just include id and date in results
.ungroup() // stop performing actions on the group
.map((row) => row('reduction').nth(0)); // map the results only retrieving the first row of each group, the latest for each id
如果 the_id
字段不是唯一的,则此查询将 return 最近 2 周内创建的每个 the_id
的最新记录。
使用二级索引
为了使上面的查询更 efficient/performant 你可以在 created_date
上放置一个索引,然后使用 between()
命令查找最近 2 周内的所有创建日期。
首先在日期字段上创建索引:
r.table('the_table').indexCreate('created_date');
然后您可以使用它来更有效地过滤您的 table。
r.table('the_table')
.between(r.now().sub(86400*84), r.now(), { index: 'created_date'})
.group('the_id')
.orderBy(r.desc('created_date'))
.pluck('the_id', 'created_date')
.ungroup()
.map((row) => row('reduction').nth(0))
我有一个 table,其中一些行如下所示:
{
"id": "12345"
"created_date": Fri May 27 2016 22:06:25 GMT+00:00 ,
} {
"id": "6789"
"created_date": Mon May 30 2016 07:48:35 GMT+00:00 ,
}
etc...
我试图首先通过仅获取从今天起不迟于 2 周前创建的行来过滤行。
然后我试图通过仅获取唯一 ID(无重复)但仍然是最新的 ID 来进行过滤。
此过滤可以反向进行,如果这样效率更高的话。
与此伪代码类似的内容:
r.db().table().filter( r.time(r.row['created_date']) > r.now()-2_weeks).filter(latest-uniques-only)
这里有两个选项可以达到预期的效果。
使用过滤器和分组
您可以使用以下查询来执行此查找(代码使用 Javascript API 并通过数据资源管理器在 table 上进行了测试):
r.table('the_table')
.group('the_id') // group by the id
.filter((row) => {
return row('created_date').gt(r.now().sub(86400*14)); // only include records from the last 14 days
})
.orderBy(r.desc('created_date')) // order by latest first
.pluck('the_id', 'created_date') // just include id and date in results
.ungroup() // stop performing actions on the group
.map((row) => row('reduction').nth(0)); // map the results only retrieving the first row of each group, the latest for each id
如果 the_id
字段不是唯一的,则此查询将 return 最近 2 周内创建的每个 the_id
的最新记录。
使用二级索引
为了使上面的查询更 efficient/performant 你可以在 created_date
上放置一个索引,然后使用 between()
命令查找最近 2 周内的所有创建日期。
首先在日期字段上创建索引:
r.table('the_table').indexCreate('created_date');
然后您可以使用它来更有效地过滤您的 table。
r.table('the_table')
.between(r.now().sub(86400*84), r.now(), { index: 'created_date'})
.group('the_id')
.orderBy(r.desc('created_date'))
.pluck('the_id', 'created_date')
.ungroup()
.map((row) => row('reduction').nth(0))