如何基于Firebase中的多个条件进行查询? [英] How to query based on multiple conditions in Firebase?

查看:21
本文介绍了如何基于Firebase中的多个条件进行查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下结构:

{
  "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活动 = '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?

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);
            });
        });
    });
}

由于您要搜索所有用户,因此代码会遍历所有用户(通常应该在添加或修改用户时执行此操作,因此可以通过侦听 child_ 事件).然后将相关节点添加到索引中:一个用于年龄,一个用于每个类别.

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.

在你的数据上运行这个之后,index 节点看起来像这样:

After running this on your data, the index node looks like this:

{
  "21": {"123":true},
  "30":{"124":true},
  "bike":{"124":true},
  "horse":{"123":true}
}

因此,您可以通过以下方式获得 20 到 30 岁之间的所有用户:

So with that you can get all users that are between 20 and 30 by:

ref.orderByKey().startAt("20").endAt("30").on('child_added'

或所有具有马"活动的用户:

Or all users with a "horse" activity by:

ref.orderByKey().equalTo("horse").on('child_added'

这篇关于如何基于Firebase中的多个条件进行查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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