我有一个从 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"
}
...
}
最佳答案
您似乎误解了 .indexOn
的作用,以及它与 orderByChild("time")
的关系。
要从按时间
排序(也可能按时间过滤)的内容
中检索子节点,您始终需要调用orderByChild("time")
.
如果您定义索引(使用".indexOn": "time"
),则排序和过滤将在服务器上完成。
如果没有索引,content
下的所有数据都将下载到客户端,并且排序/过滤将在客户端执行。
因此,.indexOn
不能替代 orderByChild
。相反,两者携手合作来执行有效的数据排序和过滤。
关于java - Firebase .indexOn 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56727546/