Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase - iOS SDK - filter by child value

I'm trying to use Firebase to setup a new project and I'm struggling with the non-relational DB and the query system. I have read the guidelines, especially those regarding the data structure. Here is my use case: I have to handle some products and each one has a name and a family, this one is an entity too. I have created the structure below trying to follow the guidelines and the examples.

{
    "families" : [ {
      "name" : "easy",
      "products" : [ 10, 11 ]
    }, {
      "name" : "ir33",
      "products" : [ 12, 13 ]
    } ],
    "products" : {
      "10" : {
          "family" : 0,
          "name" : "Matita"
      },
      "11" : {
          "family" : 0,
          "name" : "Penna"
      },
      "12" : {
          "family" : 1,
          "name" : "Gomma"
      }
    }
}

Given a family, I would like to select all the products of that one. My first solution is to access the family, retrieve the array of IDs and then perform the requests (one for each ID). It works, but this approach potentially leads to a tons of requests. Is there a better way to gain that? For example, I'm trying with this one but It doesn't work:

ref.child("products").queryOrderedByChild("family").queryEqualToValue("0", childKey: "family").observeSingleEventOfType(.Value, withBlock: { snap in
    print("snap \(snap)")
})

But it always prints Snap (products) <null>.

UPDATE

I can access the products of a given family with this query:

ref.child("products").queryOrderedByChild("family").queryEqualToValue(0).observeSingleEventOfType

Btw, Now I have this warning while running my tests:

[FirebaseDatabase] Using an unspecified index. Consider adding ".indexOn": "family" at /products to your security rules for better performance

Thanks in advance for your help!

like image 753
Zeb Avatar asked Mar 10 '23 23:03

Zeb


2 Answers

What about this:

ref.queryOrderedByChild("family").queryEqualToValue(0).observeSingleEventOfType(.Value, with: { snap in  
    print("snap \(snap)")
})

Update regarding to update of question:

Add this to your database rules in the firebase console (see also screenshot). Don't forget to hit the "Publish" button:

"products": {
  ".indexOn": "family"
}

enter image description here

like image 127
ronatory Avatar answered Mar 28 '23 14:03

ronatory


Here is the correct solution, I'm looking to solve the warning too:

ref.child("products").queryOrderedByChild("family").queryEqualToValue(0).observeSingleEventOfType(.Value, withBlock: { snap in
        print("snap \(snap)")
        expectation.fulfill()
    })

Please look at @ronatory answer to handle the warning!

like image 20
Zeb Avatar answered Mar 28 '23 14:03

Zeb