How to query based on multiple conditions in Firebase?

后端 未结 1 1935
臣服心动
臣服心动 2020-12-06 03:42

I have this following structure:

{
  \"users\" : {
    \"123\" : {
      \"activities\" : {
        \"horse\" : \"horse\",
        \"bike\" : \"bike\"
               


        
相关标签:
1条回答
  • 2020-12-06 04:34

    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.orderByKey().startAt("20").endAt("30").on('child_added'
    

    Or all users with a "horse" activity by:

    ref.orderByKey().equalTo("horse").on('child_added'
    
    0 讨论(0)
提交回复
热议问题