Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying below AutoID's in Firebase

Tags:

Results
- auto generated ID
  - auto generated ID
       value1: abc
       value2: def

I want to be able to query where "value2" is equal to some specific value. I start with a reference:

let ref = FIRDatabase.database().reference().child("Results")

Since I don't know the auto generated ID's in order to supply a path do I need to get them first in order to get down to value where I can use .queryEqualToValue? If so am I not just grabbing every record to look for a value versus using some kind of index to grab only those where value2 is equal to a value?

In the end I would like a query that returns all "records" where value2 is equal to a certain value. It feels like I need to iterate through every record to do that. I feel like I am missing something here.

Update:

I've tried:

self.ref.queryOrderedByKey().queryEqual(toValue: "def", childKey: "value2").observeSingleEvent(of: .value, with: {(snapshot) in
            print(snapshot) })

This crashes with an error I give in comments below.

I've tried:

self.ref.queryOrdered(byChild: "value2").queryEqual(toValue: "def").observeSingleEvent(of: .childAdded, with: {(snapshot) in

This never executes the closure. If I change the observer to ".value"it returns null.

If I do this:

self.ref.queryOrdered(byChild: "value2").observeSingleEvent(of: .childAdded, with: {(snapshot) in

It will actually sort the data properly. It won't sort properly with ".value" Regardless, adding queryEqual then doesn't work as described above.

like image 856
C6Silver Avatar asked Nov 21 '16 05:11

C6Silver


1 Answers

Firebase Database queries properties one level deeper than the location where you run them. They cannot contain a dynamic path under that.

Since you're querying from /Results, you can order by/filter on properties under /Results/$id/PropertyName.

To allow ordering/filtering of all items on properties under /Results/$id1/$id2/PropertyName you will need to change/augment your data structure. For example:

ResultValues
   -auto_generated_ID1_auto_generated_ID2_value1
       value: abc
       path: "auto generated ID/auto generated ID"
   -auto_generated_ID1_auto_generated_ID2_value2
       value: def
       path: "auto generated ID/auto generated ID"

Now you can query with:

ref.child("ResultValues")
   .queryOrderedByChild("value")
   .queryEqual(toValue: "def")
   .observeSingleEvent(of: .value, with: {(snapshot) in
            print(snapshot) })
like image 187
Frank van Puffelen Avatar answered Oct 13 '22 11:10

Frank van Puffelen