Firebase Queries

Say I have a structure like this:

-users -user1_uid name distance age 

How can I make a request like (Find users with a distance <100 and age from 20 to 25)?

I tried the standard method

  let recentPostsQuery = (ref?.child("users").queryOrderedByChild("age").queryStartingAtValue("20"))! 
Problem

M, that is, it seems impossible to query for multiple children (for example, combining age and distance filtering). Has anything changed in this regard compared to Firebase a few months ago? I believe that filtering them locally after the first request is not an option, since there could potentially be thousands of objects.

+5
source share
2 answers

My first choice would be to request for all users from 20 to 25, and then filter the code for those 100.

The question is that filtering in the code is not an option, but I wanted to enable it for completeness in a situation where it was several thousand nodes or less:

  struct User { //starting with a structure to hold user data var firebaseKey : String? var theAge: Int? var theDistance: Int? } var userArray = [User]() //the array of user structures usersRef.queryOrderedByChild("age").queryStartingAtValue(20) .queryEndingAtValue(25).observeEventType(.Value, withBlock: { snapshot in for child in snapshot.children { //.Value so iterate over nodes let age = child.value["age"] as! Int let distance = child.value["distance"] as! Int let fbKey = child.key! let u = User(firebaseKey: fbKey, theAge: age, theDistance: distance) userArray.append(u) //add the user struct to the array } //the array to contain the filtered users var filteredArray: [User] = [] filteredArray = userArray.filter({$0.theDistance < 100}) //Filter it, baby! //print out the resulting users as a test. for aUser in filteredArray { let k = aUser.firebaseKey let a = aUser.theAge let d = aUser.theDistance print("array: \(k!) \(a!) \(d!)") } }) } 

Now a potential super simple answer.

  let usersRef = self.myRootRef.childByAppendingPath("users") usersRef.queryOrderedByChild("age").queryStartingAtValue(20) .queryEndingAtValue(25).observeEventType(.ChildAdded, withBlock: { snapshot in let distance = snapshot.value["distance"] as! Int if distance < 100 { let age = snapshot.value["age"] as! Int let fbKey = snapshot.key! print("array: \(fbKey) \(age) \(distance)") } }) 

Note that we use .ChildAdded instead of .Value, so each node is read one at a time - if the distance is not what we want, we can ignore it and move on to the next.

+8
source

Firebase cannot always combine conditions. How to execute a query based on several conditions in Firebase?

But, using the new Firebase API, this post may give some hints: A request based on multiple offers in firebase

+1
source

All Articles