1

Firebase Data Structure

{
  "books": {
    "-KaKjMMw-WQltqxrGEmj": {
      "categories": {
        "cat1": true,
        "cat2": true
      },
      "author": "user1",
      "title": "event1"
    },
    "-KaKjMMw-WQltqxrGEmk": {
      "categories": {
        "cat1": true,
        "cat2": false
      },
      "author": "user1",
      "title": "event2"
    }
  }
}

Query To find all books of a particular author

FNode.testNode.child("books")
    .queryOrderedByChild("author")
    .queryEqualToValue("user1")
    .observeEventType(.Value) { (snapshot) in
    print(snapshot)
}

Question:

I want to find all the books belonging to cat1. Couldn't figure out the query to do that.

Community
  • 1
  • 1
Prajeet Shrestha
  • 7,978
  • 3
  • 34
  • 63

1 Answers1

2

After a lot of hit and trial, finally got my answer.

For the above structure. If you want to find all the books belonging to cat1 Here is the query for that:

FNode.testNode.child("books")
    .queryOrderedByChild("categories/cat1").queryEqualToValue(true)
    .observeEventType(.Value) { (snapshot) in
    print(snapshot)
}

Note: FNode.testNode could be any node of type FIRDatabaseReference

To Firebase Team: Can you please include a sample of all possible firebase queries in data structures and put it alongside firebase docs. It's kind of hit-and-trial for us now.

Prajeet Shrestha
  • 7,978
  • 3
  • 34
  • 63
  • 1
    This works, but means you'll need to [define an index in your Firebase security rules](https://firebase.google.com/docs/database/security/indexing-data) for each category. For a more maintainable solution, see my answer here: http://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value – Frank van Puffelen Jan 13 '17 at 04:59
  • Sure thanx for the link. – Prajeet Shrestha Jan 13 '17 at 04:59
  • Also what are the disadvantage of querying without putting indexes in database rules? Will it really be slow? – Prajeet Shrestha Jan 13 '17 at 05:04
  • It will download all data to the client and filter client-side. If that doesn't sound scary, read it again. Or turn on 2G. :-) – Frank van Puffelen Jan 13 '17 at 05:11
  • So if I query on books node. And put queries like above, it will download all the data of books node and filter client side? – Prajeet Shrestha Jan 13 '17 at 05:22