【问题标题】:Firebase - index on .value not giving sorted resultsFirebase - .value 上的索引未给出排序结果
【发布时间】:2017-07-30 10:34:56
【问题描述】:

我有一个像这样的数据结构:

{
   "inbox_events": {
      "from_users": {
         "uid1": {
            "uid2": 1501337181,
            "uid3": 1501337183,
            "uid4": 1501337179
         },
         "uid2" : {
            "uid6": 1501337284,
            "uid1": 1501337295
         }
      }
   }
}

遵循以下规则:

{
   "rules": {
      ".read": "auth != null",
      ".write": "auth != null",
      "inbox_events": {
         "from_users": {
            "$userId": {
               ".indexOn": ".value"
            }
         }
      }
   }
}

问题:我不明白为什么价值索引不起作用。在 firebase 控制台中,每个 $userId 的条目仍按字母顺序排序,如果我执行 queryOrderedByValue,则不会得到排序结果。

我是否误读了 Firebase 文档?

提前致谢!


编辑:

具体来说,我正在尝试像这样查询数据:

let queryRef = Database.database().reference().child("inbox_events").child("from_users").child("uid1").queryOrderedByValue()
queryRef.observe(.value, with: { (snapshot) in
    print("key: \(snapshot.key), value: \(snapshot.value)")
})

为了在uid1节点处得到uids的降序列表。

【问题讨论】:

  • 发布一些代码。另外,请指定您使用的平台(Android、iOS、Web、Admin SDK、REST API 等)
  • @DimaRostopira:添加了我打算做的事情,平台是由 Frank Van P 正确编辑的 iOS。
  • 有点不清楚您要做什么;您想按值查询,但 uid 是键。此外,Firebase 不提供降序排序选项,尽管有一些方法可以做到这一点。最后,.index 不会直接影响项目的排序方式——它是查询的性能增强。你能澄清一下预期的输出是什么吗?
  • @Jay:当然,抱歉。预期输出为:["uid3", "uid2", "uid4"] 因为 1501337183 > 1501337181 > 1501337179。

标签: ios firebase firebase-realtime-database


【解决方案1】:

这很容易被忽视。

结果被组合成一个快照,当打印出来时,数据被转换成一个失去顺序的字典。

为了保持正确的顺序,迭代返回的快照。

这是带有转换后快照的代码,然后是如何迭代快照以维护顺序

let queryRef = self.ref.child("inbox_events").child("from_users").child("uid1").queryOrderedByValue()
queryRef.observe(.value, with: { (snapshot) in

    //converts to dict
    print("key: \(snapshot.key), value: \(snapshot.value)")

    //keeps the order
    for child in snapshot.children {
        let snap = child as! DataSnapshot
        print("key: \(snap.key), value: \(snap.value)")
    }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 2017-01-07
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多