【问题标题】:Return all data by specific userID sorted by newest date in Fauna DB按 Fauna DB 中按最新日期排序的特定用户 ID 返回所有数据
【发布时间】:2022-01-20 05:14:02
【问题描述】:

我正在尝试进行 Fauna 查询,该查询将检索特定用户的所有数据,按最新创建的排序。

在他们的文档 (https://docs.fauna.com/fauna/current/tutorials/indexes/sort#multiple) 中有如何处理多个数据的步骤,您必须在值中指定这些数据,因为集合中有很多字段,有时我不知道他们的名字我想要结果像这样

"data": [
    {
      "ref": Ref(Collection("Planets"), "267081152090604051"),
      "ts": 1590967285200000,
      "data": {
        "name": "Jupiter",
        "type": "GAS",
        "userID": "12344",
        "created": "1639665397555"
      }
    },
    {
      "ref": Ref(Collection("Planets"), "267081181884842515"),
      "ts": 1590967313610000,
      "data": {
        "name": "Saturn",
        "type": "GAS",
        "userID": "12344",
        "created": "1639665397446"

      }
    }
  ]
}

所以可以这样查询吗:

SELECT * FROM plantes WHERE userID="12233" ORDER BY created ASC

没有指定要检索哪些字段,我想要它们全部,无论名称只是通过 UserID 过滤和排序。

这是我创建的索引:

   CreateIndex({
      name: "get_user_planets_3",
      source: Collection("planets"),
       terms: [
        {
          field: ["data", "userID"]
        }
      ],
      values: [
        { field: ["data", "created"], reverse: true },
        { field: ["data", "name"] },
        { field: ["data", "type"] },
      ]
    })

但我不想指定我想要的字段名称,无论名称只是按日期排序。

谢谢

【问题讨论】:

    标签: faunadb


    【解决方案1】:

    为了检索所选集的所有数据,请在索引values 中返回ref 字段,然后返回文档中的MapGet

    使用这样的索引:

    CraeteIndex({
      name: "get_user_planets_3",
          source: Collection("planets"),
           terms: [
            {
              field: ["data", "userID"]
            }
          ],
          values: [
            { field: ["data", "created"], reverse: true },
            { field: ["ref"] } // <-- use this to retrieve the whole Document
          ]
    })
    

    您可以通过如下请求检索所有文档数据:

    Map(
      Paginate(Match(Index("get_user_planets_3"), "12233")),
      Lambda(
        // each Index value is passed to the mapping function
        ["created", "ref"],
        Get(Var("ref"))
      )
    )
    

    请注意,由于 Get 调用,每个文档至少需要 1 次读取操作。如果您想节省读取成本,那么您应该优化您需要接收哪些数据的查询。甚至有多种方法可以让您的集合拥有多个索引,并让调用者根据需要选择哪些索引。对于您自己的应用程序,这一切都是需要考虑的权衡。

    【讨论】:

    • 虽然这是一种不寻常的方式,但与 sql 查询相比,它正在完成这项工作......非常感谢您
    猜你喜欢
    • 2018-05-16
    • 2020-07-26
    • 2016-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多