Korken55
Korken55

Reputation: 253

Firebase filter data by name and city in swift2

I´m trying to get data from Firebase depending on the name and city from object. My firebase tree looks like this:

MYAPP
Object:
   - 12837291ß2837(a random ID):
     "name": "test"
     "city": "Hong Kong"
   - 12382133193u2:
     "name": "test"
     "city": "Paris"
   - 2137829128738: 
     "name": "test2"
     "city": "Frankfurt"

So for example i just want to get the Object where the name is "test" and the city is "Hong Kong".

i tried sth like this but i dont get any Data:

let ref = FIRDatabase.database().referenceFromURL("https://myRef")
    ref.queryOrderedByChild("Object").queryEqualToValue("test").observeEventType(.ChildAdded) { (snapshot) in
        print(snapshot)
    }

I also added rules in Firebase like :

".indexOn": "Object"

Upvotes: 0

Views: 480

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

Two main problems:

  1. your query doesn't match your data structure
  2. you can only filter on one property.

Your query doesn't match your data structure

To sort/filter you first specify the property that you want to filter on and then the filtering operation. Since the value you specify is from the name property, the correct query is:

let ref = FIRDatabase.database().referenceFromURL("https://myRef")
let query = ref.queryOrderedByChild("name").queryEqualToValue("test")
query.observeEventType(.ChildAdded) { (snapshot) in
    print(snapshot)
}

You can only filter on one property

Firebase Database only supports ordering/querying on a single properties. See Query based on multiple where clauses in firebase.

Upvotes: 1

Related Questions