Firebase实时数据库:如何正确索引键值对 [英] Firebase Realtime DB: Howto index properly on key-value pair

查看:260
本文介绍了Firebase实时数据库:如何正确索引键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个Firebase实时数据库:

I have this Firebase Realtime Database:

{      
  "groupUsers" : {
    "group1key" : {
      "user1key" : "admin"
    },
    "group2key" : {
      "user1key" : "admin",
      "user2key" : "readonly",
      "user3key" : "readwrite"
    }
  }
}

在我的Android应用程序中,我这样查询

In my Android app I query that like this

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("groupUsers");
ref.orderByChild(auth.getCurrentUser().getUid()).startAt("").addValueEventListener() {...}

产生警告:


使用未指定的索引。考虑将.indexOn...添加到您的安全和Firebase数据库规则中以获得更好的性能

Using an unspecified index. Consider adding ".indexOn" ... to your security and Firebase Database rules for better performance

如何正确索引?当数据增长时,我担心我的应用程序将变得超级慢速查询未编入索引的数据。

How to index properly? When the data is growing I fear that my app will become super slow querying on not-indexed data.

我已经在我的规则文件中尝试索引值:

I already tried in my rules file to index the values:

".indexOn": ".value"

但这只有在数据是标量但它们是键值对时才有效( user1key:admin)。

but that would work only if the data are scalars but they are key-value pairs ("user1key" : "admin").

我不能在我的规则文件中添加索引,如下所示:

I can't just add an index in my rules file like this:

".indexOn": ["user"]

因为这需要一个像这样的常量属性名称:

since that requires a constant property name like this:

{ "groupUsers" : {
    "group1key" : {
      "name" : "user1"
    }        
  }
}

但我的名字就像

"user1key" : "admin",
"user2key" : "readonly",
"user3key" : "readwrite"


推荐答案

没有为这种结构预先创建索引的方法。在我的回答中我已经介绍了这种结构这里此处和新的Firestore文档(在此方面的工作方式类似) )甚至有一个关于它的文档页面

There is no way to pre-create the indexes for such a structure. I've covered this type of structure in my answer here and here and the new Firestore documentation (which works similarly in this aspect) even has a documentation page about it.

建议以一种允许在另一个方向进行查找的方式存储数据。使用当前结构,您可以有效地查找组中的用户。要允许查找用户的组,请添加以下结构:

The recommendation is to store data in a way that allows this lookup in the other direction too. With your current structure you can efficiently look up the users in a group. To also allow looking up the groups for a user, add this structure:

{      
  "usersGroups" : {
    "user1key" : {
      "group1key" : "admin",
      "group2key" : "admin"
    },
    "user2key" : {
      "group2key" : "readonly",
    },
    "user3key" : {
      "group2key" : "readwrite"
    }
  }
}

这篇关于Firebase实时数据库:如何正确索引键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆