C6Silver C6Silver - 1 year ago 88
Swift Question

Querying below AutoID's in Firebase

- 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
? 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
is equal to a value?

In the end I would like a query that returns all "records" where
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.


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
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
Regardless, adding
then doesn't work as described above.

Answer Source

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:

       value: abc
       path: "auto generated ID/auto generated ID"
       value: def
       path: "auto generated ID/auto generated ID"

Now you can query with:

   .queryEqual(toValue: "def")
   .observeSingleEvent(of: .value, with: {(snapshot) in
            print(snapshot) })
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download