【问题标题】:Using an unspecified index. Your data will be downloaded使用未指定的索引。您的数据将被下载
【发布时间】:2021-08-05 07:26:41
【问题描述】:

使用未指定的索引。您的数据将在客户端下载和过滤。考虑将作者的 '".indexOn": "name"' 添加到您的安全和 Firebase 数据库规则中以获得更好的性能

这是什么意思? 数据库有问题吗?

Query query = FirebaseDatabase.getInstance().getReference("authors").orderByChild("name").equalTo(str);
        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot ds: dataSnapshot.getChildren()) {
                    search_authors author = ds.getValue(search_authors.class);
                    Log.println(Log.DEBUG, "Test", author.name);
                }
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                throw  error.toException();
            }
        });

【问题讨论】:

    标签: java android firebase firebase-realtime-database


    【解决方案1】:

    您看到的警告与您的客户端代码无关,而是您应该在服务器端进行的优化(在本例中,针对 Firebase 实时数据库)。

    在您的代码中,您使用getReference("authors").orderByChild("name").equalTo(str),它表示“对于'/authors' 下的所有数据,查找'name' 等于给定字符串的作者”。

    当您的客户端 SDK 向服务器发出此查询时,它会发回 /authors 下的 所有内容(如果权限允许)并说“嘿,我没有 'name 的索引',你能最终处理它吗?”。然后,SDK 会筛选发回的数据,并提取所有 'name' 等于您提供的字符串的文档。它还会显示您看到的警告。

    在开发过程中,这很好,因为您正在处理少量数据,但是当 /authors 开始包含数百个条目时,您最终会下载所有条目,而您可能只需要其中一个 - 这是效率低下。在将代码部署到大众之前,您应该将 ".indexOn": "name" 添加到您的 security rules in the Firebase Console 以构建此查询所需的索引。如何做到这一点是documented here

    例如,您可以使用以下规则:

    {
      "rules": {
        "authors": {
          ".read": "auth != null", // any logged in user can read anything under /authors
          ".indexOn": ["name"], // index all authors by the 'name' field
          
          "$authorId": {
            // only the owner can write to their own data
            ".write": "auth != null && auth.uid == $authorId", 
          }
        }
      }
    }
    

    创建这样的索引后,服务器只能发回匹配的数据而不是全部,并且警告停止出现。然后对您计划查询的任何其他字段重复此操作,例如“likeCount”、“commentCount”、“createdAt”、“lastPostAt”等根据需要

    【讨论】:

    • 非常感谢你)
    猜你喜欢
    • 2022-11-16
    • 2021-11-10
    • 2019-05-04
    • 2017-10-08
    • 2021-12-31
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    相关资源
    最近更新 更多