添加和".indexOn":“.value"纳入Firebase规则 [英] Adding and ".indexOn": ".value" into Firebase Rules
问题描述
我正在研究AngularJS和Firebase,并且正在玩一个简单的ChatApp,只是为了了解代码.
I'm studying AngularJS and Firebase and I'm playing with a simple ChatApp, just to understand the code.
我的Firebase数据库结构是这样的:
My Firebase DB structure is like this:
"chat": {
"messages": {
"chat1": { [ list of messages ] },
"chat2": { [ list of messages ] }
},
"rooms": {
"chat1": {
"users": {
"user1": true,
"user2": true
}
},
"chat2": {
"users": {
"user2": true,
"user3": true
}
}
}
}
由于具有Firebase保护规则,我无法在用户节点中添加聊天链接,因此我必须通过在App上使用 orderByChild()
查询进行Firebase查询来检索用户的聊天室启动.
Due to Firebase protection Rules I can't add chat link in the user node, than I necessary have to do a Firebase query to retrieve chat rooms for user, using orderByChild()
query on App Start Up.
使用Firebase很简单,因为我可以使用以下方式检索所有聊天记录:
Using Firebase is simple than I can retrieve all chat using:
var chatLink = firebase.database().ref('chat/rooms');
chatLink
.orderByChild('users/' + userId)
.equalTo(true)
.once('value', function(chatSnap){
/* Do Some Stuff Here */
});
一切正常,但是我在控制台中收到警告:
Every thing work well, but I'm receiving a warning in the console:
FIREBASE警告:使用未指定的索引.考虑在/chat/rooms的安全规则中添加".indexOn":"users/{userId}"以提高性能
FIREBASE WARNING: Using an unspecified index. Consider adding ".indexOn": "users/{userId}" at /chat/rooms to your security rules for better performance
在网络上搜索时,我发现对于变量 orderByChild()
查询,我可以在Firebase规则中使用 .indexOn:.value
.
Searching on the web, I found that for variable orderByChild()
query, I can user .indexOn: .value
in my Firebase Rules.
我尝试添加此规则:
{
"rules": {
"chat": {
"rooms": {
".indexOn": ".value"
}
}
}
}
但是我仍然总是收到该警告.我该如何解决?
But I'm still receive always that warning. How can i fix it?
非常感谢!
推荐答案
要对该结构建立索引以实现高效查询,您必须为每个用户添加一个索引:
To index this structure to allow efficient querying, you have to add an index for each user:
{
"rules": {
"chat": {
"rooms": {
".indexOn": ["users/user1", "users/user2"]
}
}
}
}
这将无法维护,因为您可能会动态添加用户.
That won't be maintainable, since you're likely adding users dynamically.
与NoSQL数据库一样,这意味着您必须扩展/调整数据模型以允许所需的用例.除了为您的用户查询房间外,还要保留每个用户的房间列表(除了您当前的数据之外):
As usual with NoSQL databases, this means you have to expand/adapt your data model to allow the use-case you want. Instead of querying the rooms for their users, keep a list of the rooms for each user (in addition to your current data):
"user_rooms": {
"user1": {
"chat1": true
},
"user2": {
"chat1": true,
"chat2": true
}
"user3": {
"chat2": true
}
现在,您甚至可以查询用户的聊天室.
Now you can look up the chat rooms for a user without even needing to query.
另请参阅 Firebase查询中有关此分类问题的答案如果child的child包含值.
这篇关于添加和".indexOn":“.value"纳入Firebase规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!