如何根据Firebase中的多个条件进行查询? [英] How to query based on multiple conditions in Firebase?
问题描述
{
users:{
123 :{
activities:{
horse:horse,
bike:bike
},
age:21
},
124:{
activities:{
bike:bike
},
age:30
$ b我试图做类似于
SELECT * FROM users WHERE(activities ='horse'OR activities ='bike')AND age> = 21
我能否就此得到一些指示?如果我没有正确地构建数据,我还可以在那里得到一些提示吗?
var ref = new Firebase('https: //yours.firebaseio.com/users');
var index = new Firebase('https://yours.firebaseio.com/index');
函数createIndex(){
ref.once('value',function(snapshot){
snapshot.forEach(function(userSnapshot){
var user = userSnapshot.val );
index.child(user.age).child(userSnapshot.key()).set(true);
Object.keys(user.activities).forEach(function(activity){
index.child(activity).child(userSnapshot.key()).set(true);
});
});
});
$ b $ p
$ b因为你想跨所有用户搜索,代码循环遍历所有用户通常应该在添加或修改用户时这么做,通过监听 child _
events)。然后它将相关节点添加到索引:一个用于年龄,一个用于每个类别。
在数据上运行这个之后,索引
{
21:{123: true},
30:{124:true},
bike:{124:true},
horse:{123
$ b 所以你可以得到20到30之间的所有用户:
$ b $ ref.startAt(20)。endAt(30)on('child_added'
或所有使用马活动的用户:
<$ p $('child_added'
I have this following structure:
{
"users" : {
"123" : {
"activities" : {
"horse" : "horse",
"bike" : "bike"
},
"age" : 21
},
"124" : {
"activities" : {
"bike" : "bike"
},
"age" : 30
}
}
I am trying to do something similar to:
SELECT * FROM users WHERE (activities = 'horse' OR activities = 'bike') AND age >= 21
Can I please get some pointers on this? If I didn't structured the data properly, can I also get some tips there?
edit: jsfiddle
解决方案 I will mark this question as a duplicate, but this code might be helpful for you to get started building your own search index:
var ref = new Firebase('https://yours.firebaseio.com/users');
var index = new Firebase('https://yours.firebaseio.com/index');
function createIndex() {
ref.once('value', function(snapshot) {
snapshot.forEach(function(userSnapshot) {
var user = userSnapshot.val();
index.child(user.age).child(userSnapshot.key()).set(true);
Object.keys(user.activities).forEach(function(activity) {
index.child(activity).child(userSnapshot.key()).set(true);
});
});
});
}
Since you want to search across all users, the code loops over all users (you should normally do this when the users are added or modified, so by listening for the child_
events). It then adds the relevant nodes to the index: one for the age and one for every category.
After running this on your data, the index
node looks like this:
{
"21": {"123":true},
"30":{"124":true},
"bike":{"124":true},
"horse":{"123":true}
}
So with that you can get all users that are between 20 and 30 by:
ref.startAt("20").endAt("30").on('child_added'
Or all users with a "horse" activity by:
ref.equalTo("horse").on('child_added'
这篇关于如何根据Firebase中的多个条件进行查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!