【问题标题】:How do I create an index in Fauna DB that returns sorted data in key value pairs如何在 Fauna DB 中创建以键值对形式返回排序数据的索引
【发布时间】:2020-10-17 12:58:44
【问题描述】:

我正在尝试创建一个索引,该索引返回带有键的对象中的排序数据。 我的集合的默认索引返回如下内容:

{
  "ref": Ref(Collection("posts"), "251333584234742292"),
  "ts": 1583632773120000,
  "data": {
    "title": "A Great Title",
    "sort_date": "2019-12-11",
    "post_type": "blog",
    "status": "published",
   }
},...

我用这段代码在 shell 中创建了一个索引:

CreateIndex({
  name: "posts_sort_date_desc",
  source: Collection("posts"),
  values: [
    { field: ["data", "sort_date"], reverse: true },
    { field: ["data", "title"] },
    { field: ["data", "post_type"] },
    { field: ["data", "status"] },
    { field: ["ref"] }
  ]
}

当我查看这个新索引时,排序是正确的,但它看起来像一个没有键的数组,如下所示:

[
  "2019-12-11",
  "A Great Title",
  "",
  "published",
  Ref(Collection("posts"), "254000373213168147")
], ...

有没有办法创建一个排序索引,只包含我需要的键值对数据?我浏览了文档,但无法弄清楚。谢谢。

【问题讨论】:

    标签: faunadb


    【解决方案1】:

    您的问题的简短回答是:“不,没有”,但您的问题可能有解决方案(我需要更好地理解您试图解决的问题)。索引将总是返回数据数组,因为它们是这样构造的,而 FaunaDB 让您可以访问索引的原始功能。我们不会试图变得聪明并解释您可能想要的东西。

    (免责声明,我没有测试代码,这里是晚上 11:30,所以我几乎要注销 :) 但仍然想帮助你)

    也就是说,有两种选择:

    • 不要让自己基于索引中的值,而是取出 ref 并编写一个 Map/Get 来获取基础文档,它作为一个对象出现。每个 Get 虽然也需要读取,所以这是一个权衡,但是当添加您不想排序但想要返回的新属性时,它将更加灵活(否则您将不得不重新创建索引)。
    Map(
       Paginate(Match(Index('your_index_name'))),
       Lambda(['sort_date', 'title', 'post_type', 'status', 'ref'], Get(Var('ref')))
    )
    
    • 保持索引不变,一旦获得这些值,您就可以轻松地在这些索引页面上编写 Map(在 FQL 中)并通过返回一个 Object 来重构结果。这看起来像
    Map(
       Paginate(Match(Index('your_index_name'))),
       Lambda(['sort_date', 'title', 'post_type', 'status', 'ref'],
         {
           ref: Var('ref'),
           sort_date: Var('sort_date'),
           title: Var('title'),
           post_type: Var('post_type'),
           status: Var('status')
         }
       )
    )
    
    

    这应该给你一个对象数组 :)

    【讨论】:

    • 非常感谢最后一分钟的帮助。第二个选项对我来说更有意义。我仍然习惯于关系数据库。也许我应该更笼统地问一下,返回博客或事件列表的最新帖子的标准程序是什么?
    猜你喜欢
    • 1970-01-01
    • 2022-01-20
    • 2019-09-02
    • 1970-01-01
    • 2020-09-27
    • 2018-04-08
    • 1970-01-01
    • 2018-09-13
    • 2019-03-15
    相关资源
    最近更新 更多