0

我有一个表,其中一些行看起来像这样:

{
  "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...
  1. 我试图首先通过从今天起不迟于 2 周前创建的行来过滤行。

  2. 然后我试图通过只获取唯一的 id(没有重复)但仍然是最新的 id 来过滤。

如果这样更有效,则可以反向进行此过滤。

类似于此伪代码的内容:

r.db().table().filter( r.time(r.row['created_date']) > r.now()-2_weeks).filter(latest-uniques-only)
4

1 回答 1

2

以下是实现预期结果的两个选项。

使用过滤器和组

您可以使用以下查询来执行此查找(代码使用 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))
于 2016-06-02T18:11:01.430 回答