【问题标题】:RethinkDB index for filter + orderby过滤器 + orderby 的 RethinkDB 索引
【发布时间】:2013-11-02 21:41:49
【问题描述】:

假设一个 cmets 表具有以下结构:

id | author | timestamp | body

我想使用索引来有效地执行以下查询:

r.table('comments').getAll("me", {index: "author"}).orderBy('timestamp').run(conn, callback)

我可以使用其他有效的方法吗?

看起来当前索引不支持表的过滤结果。为timestamp 创建索引并将其作为提示添加到orderBy('timestamp', {index: timestamp}) 时,出现以下错误:

RqlRuntimeError:索引 order_by 只能在 TABLE 上执行。在:

【问题讨论】:

    标签: rethinkdb


    【解决方案1】:

    这可以通过“作者”和“时间戳”字段上的复合索引来完成。您可以像这样创建这样的索引:

    r.table("comments").index_create("author_timestamp", lambda x: [x["author"], x["timestamp"]])
    

    然后您可以使用它来执行查询,如下所示:

    r.table("comments")
     .between(["me", r.minval], ["me", r.maxval]
     .order_by(index="author_timestamp)
    

    像 get_all 在原始查询中所做的工作之间的工作,因为它只获取具有作者“我”和任何时间戳的文档。然后我们在按时间戳排序的同一索引上执行 order_by(因为所有键都具有相同的作者。)这里的关键是每次表访问只能使用一个索引,因此我们需要将所有这些信息塞进相同的索引。

    【讨论】:

    • 是否可以对多个作者进行此操作?即您想检索作者JohnJane 的最近10 个cmets。
    【解决方案2】:

    目前无法使用索引两次将getAllorderBy 链接起来。 现在只能在表上使用索引进行排序。

    注意:带有索引的orderBy命令是orderBy({index: 'timestamp'})(无需重复key)

    【讨论】:

      【解决方案3】:

      Joe Doliner 的答案被选中,但对我来说似乎是错误的。

      首先,在between 命令中,没有指定索引器。因此between 将使用主索引。

      其次,between 返回一个选择

      table.between(lowerKey, upperKey[, {index: 'id', leftBound: 'closed', rightBound: 'open'}]) → selection
      

      orderBy 不能在带有索引的选择上运行,只有表可以使用索引。

      table.orderBy([key1...], {index: index_name}) → selection<stream>
      selection.orderBy(key1, [key2...]) → selection<array>
      sequence.orderBy(key1, [key2...]) → array
      

      【讨论】:

        【解决方案4】:

        您想要创建所谓的“复合索引”。之后,您可以有效地查询它。

        //创建复合索引 r.table('cmets') .indexCreate( 'author__timestamp', [r.row("author"), r.row("timestamp")] ) //查询 r.table('cmets') 。之间( ['我',r.minval], ['我',r.maxval], {索引:'作者__时间戳'} ) .orderBy({index: r.desc('author__timestamp')}) //or "r.asc" .skip(0) //页面 .limit(10) //国家!

        我喜欢在复合索引中使用两个下划线。这只是风格。选择如何命名复合索引并不重要。

        参考:How to use getall with orderby in RethinkDB

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-06-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多