【问题标题】:Firebase .indexOn is not working as expectedFirebase .indexOn 未按预期工作
【发布时间】:2019-06-24 04:42:00
【问题描述】:

我有一个从 Firebase 实时数据库中检索到的 content 节点。 我利用.orderByChild("time") 获取按最早时间戳排序的前 5 个博客对象的数据快照。我

我目前正在尝试使用.indexOn : "time",这样我就不必使用.orderByChild("time"),因为我期望博客对象在检索时已经按后端的时间戳排序。 (我要处理大量的博客对象,所以我想在后端使用.indexOn : "time" 而不是在前端使用orderByChild("time") 来提高效率)。目前,.indexOn 不起作用,检索时数据未按时间字段排序。

没有.indexOn的查询

// this works fine
// startAt is utilized for saving last blog object retrieved to retrieve more data

query = 
FirebaseDatabase.getInstance().getReference()
                .child("content")
                .orderByChild("time")
                .startAt(nodeId)
                .limitToFirst(5);

使用 .indexOn 查询

// this along with the Firebase rules below does not return the same result as above
// startAt is utilized for saving last blog object retrieved to retrieve more data

query = 
FirebaseDatabase.getInstance().getReference()
                .child("content")
                .startAt(nodeId)
                .limitToFirst(5);

Firebase 规则:

{
 "rules": {
 ".read": true,
 ".write": true,
 "content" : {
      ".indexOn": "time"
  }
 }
}

Firebase 中数据的 JSON 结构:

"content" : {
"blog-0001" : {
  "content_id" : "blog-0001",
  "image" : "someimage",
  "time" : 13,
  "title" : "title1",
  "type" : "blog"
},
"blog-0002" : {
  "content_id" : "blog-0002",
  "image" : "someimage",
  "time" : 12,
  "title" : "title2",
  "type" : "blog"
},
"blog-0003" : {
  "content_id" : "blog-0003",
  "image" : "someimage",
  "time" : 11,
  "title" : "title3",
  "type" : "blog"
},
"blog-0004" : {
  "content_id" : "blog-0004",
  "image" : "someimage",
  "time" : 15,
  "title" : "title4",
  "type" : "blog"
}
...
}

【问题讨论】:

    标签: java android firebase firebase-realtime-database


    【解决方案1】:

    您似乎误解了.indexOn 的作用,以及它与orderByChild("time") 的关系。

    要从content 中检索由time 排序(也可能过滤)的子节点,您将始终需要调用orderByChild("time")

    如果您定义了一个索引(使用".indexOn": "time"),那么排序和过滤将在服务器上完成。

    在没有索引的情况下,content下的所有数据都会下载到客户端,在客户端进行排序/过滤。

    所以.indexOn 不能替代orderByChild。相反,两者携手合作,对数据进行高效排序和过滤。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-24
      • 2016-10-14
      • 1970-01-01
      • 1970-01-01
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      • 2021-07-15
      相关资源
      最近更新 更多