java - Firebase .indexOn 未按预期工作

标签 java android firebase firebase-realtime-database

我有一个从 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/

相关文章:

Java 和 .NET : Base64 conversion confusion

java - 可配置的 Autowiring NullPointerException

java - 如何在 Java 中为现有的基于 Web 的应用程序构建命令行界面

android - 在 Android Studio 0.4.0 中添加新首选项屏幕的选项在哪里?

ios - Firestore 规则 - 如何允许创建但不允许更新?

java - 如何在 IntelliJ IDEA 14 中启用 "View External Documentation"选项

android - 无法在 Qt 中链接 OpenCV Android

android - 如何在交易过程中保持手机和服务器同步?

ios - Firebase,获得具有特定值(value)的 child 的直接 parent

node.js - 在 Callable Firebase Functions 中获取请求 URL