Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

(编辑: jsfiddle)

  ask by Patrioticcow translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
440 views
Welcome To Ask or Share your Answers For Others

1 Answer

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).

(由于要在所有用户之间进行搜索,因此代码会在所有用户上循环(通常应在添加或修改用户时执行此操作,因此可以侦听child_事件)。)

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:

(在数据上运行之后, index节点如下所示:)

{
  "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:

(这样一来,您可以通过以下方式获得20至30岁之间的所有用户:)

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

Or all users with a "horse" activity by:

(或通过以下方式进行“马”活动的所有用户:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...