Filter products on multiple children in Firebase

I recently asked how to filter products based on their child property (see: Filter products based on a child child in Firebase ).

As an example, my structure is as follows:

products/ product1 /author: 12345 /title: "Awesome" /category: "catA" /description: "more awesome" product2 /author: 67890 /title: "Other" /category: "catB" /description: "otherawesome" product3 /author: 12345 /title: "Billy" /category: "catB" /description: "otherawesome" 

And to filter out all products using the author of 12345 , we can simply use:

 ref.child("products").orderByChild('author').equalTo(12345)... 

However, what should I do when I have several AND statements or several OR statements?

So what if I want to filter:

  • all products with author 12345 AND category catA (returns product1 )

  • all products with author 12345 OR author 67890 (returns product1 and product3 )

In the first part I tried:

 ref.child("products").orderByChild('author').equalTo(12345).orderByChild('category').equalTo('catA')... 

but this did not work (throws an error You can't combine multiple orderBy calls )

See also: https://www.firebase.com/docs/web/guide/retrieving-data.html#section-queries

+2
source share
1 answer

From what I read here , the way to do this is to execute the first request (preferably the one that will return the smallest results), then filter another field in javascript. Another way to do this, and I would recommend it, if you frequently execute this query, creates a composite index for a query of type; Frank van Puffelin's answer in the link above gives an example of this.

 products/ product1 /author: 12345 /title: "Awesome" /category: "catA" /description: "more awesome" /author_category: "12345_catA" product2 /author: 67890 /title: "Other" /category: "catB" /description: "otherawesome" /author_category: "67890_catB" product3 /author: 12345 /title: "Billy" /category: "catB" /description: "otherawesome" /author_category: "12345_catB" 

As for the "OR", I searched for quite a while and did not find anything that could help you. I would suggest two separate queries.

+3
source

Source: https://habr.com/ru/post/1238736/


All Articles