0

This is the first question that I post at Stackoverflow, because it's the first time that I don't find here a solution for my problem.

I had a Firebase database structure like this:

{ "races" : {
    567 : {
        "distance" : 10 ,
        "date" : 1594124321 ,
        "runners" : {
            1 : "aaaaaaaaaaaaaaa" ,
            2 : "gf76dsgf45dsag7" ,
            3 : "6f4565dsa4fa6s5" ,
            4 : "lh43k2l3kj2l4kj" ,
            5 : "lklk3f4545s7c93"
        }

    },
    568 : {
        "distance" : 5 ,
        "date" : 1594135432 ,
        "runners" : {
            1 : "faskj432lk5465f" ,
            2 : "aaaaaaaaaaaaaaa" ,
            3 : "6f4565fdsgds6s5" ,
            4 : "lh43gfdsaj2l4kj"
        }

    },
    569 : {
        "distance" : 15 ,
        "date" : 1594138245 ,
        "runners" : {
            1 : "kjhkj435kkjhkjh" ,
            2 : "gkl5lj4325dsag7" ,
            3 : "6ffsdaadsgds6s5"
        }

    },
}

And what I need is to do a query for get the race id's of the races where a certain runner participate.

Example: search for the runner "aaaaaaaaaaaaaaa", and get in this case the races 567 and 568. For doing this, orderByChild it's not enought, cause I'm searching by a second level subchild.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Macarthurval
  • 178
  • 11
  • Hi. This [link](http://stackoverflow.com/questions/26700924/query-based-on-multiple-where-clauses-in-firebase) might be helpful. – Samuel Agbede Dec 05 '16 at 23:35

1 Answers1

3

You should change the your database model. Use a map instead of a list:

569 : {
    "distance" : 15 ,
    "date" : 1594138245 ,
    "runners" : {
        "kjhkj435kkjhkjh" : true ,
        "gkl5lj4325dsag7" : true ,
        "6ffsdaadsgds6s5" : true
    }

}

Please check the Best Practices: Arrays in Firebase.

Then, you can use a Query and the orderByChild method like this:

Query query = FirebaseDatabase.getInstance().getReference("races")
                  .orderByChild("runners/" + userId).equalTo(true);

Finally, you can add a ValueEventListener and obtain a list with your races.

  • 2
    Good answer Victor. But this will require adding an index for every runner, which is bound to become a maintenance problem. See http://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value for a more scalable solution, with yet another way of modeling the data. :-) – Frank van Puffelen Dec 06 '16 at 05:12