以下是实现预期结果的两个选项。
使用过滤器和组
您可以使用以下查询来执行此查找(代码使用 Javascript API 并通过数据资源管理器在表上进行测试):
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
字段不是唯一的,则此查询将返回the_id
最近 2 周内创建的每条记录的最新记录。
使用二级索引
为了使上述查询更加高效/高性能,您可以放置一个索引created_date
,然后使用该between()
命令查找过去 2 周内创建的所有日期。
首先在日期字段上创建一个索引:
r.table('the_table').indexCreate('created_date');
然后您可以使用它来更有效地过滤您的表格。
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))