Home > Blockchain >  Combining multiple Firestore queries to get specific results (with pagination)
Combining multiple Firestore queries to get specific results (with pagination)

Time:11-26

I am working on small app the allows users to browse items based on various filters they select in the view.

After looking though, the firebase documentation I realised that the sort of compound query that I'm trying to create is not possible since Firestore only supports a single "IN" operator per query. To get around this the docs says to use multiple separate queries and then merge the results on the client side.

https://firebase.google.com/docs/firestore/query-data/queries#query_limitations

Cloud Firestore provides limited support for logical OR queries. The in, and array-contains-any operators support a logical OR of up to 10 equality (==) or array-contains conditions on a single field. For other cases, create a separate query for each OR condition and merge the query results in your app.

I can see how this would work normally but what if I only wanted to show the user ten results per page. How would I implement pagination into this since I don't want to be sending lots of results back to the user each time?

My first thought would be to paginate each separate query and then merge them but then if I'm only getting a small sample back from the db I'm not sure how I would compare and merge them with the other queries on the client side.

Any help would be much appreciated since I'm hoping I don't have to move away from firestore and start over in an SQL db.

CodePudding user response:

Say you want to show 10 results on a page. You will need to get 10 results for each of the subqueries, and then merge the results client-side. You will be overreading quite a bit of data, but that's unfortunately unavoidable in such an implementation.

The (preferred) alternative is usually to find a data model that allows you to implement the use-case with a single query. It is impossible to say generically how to do that, but it typically involves adding a field for the OR condition.

Say you want to get all results where either "fieldA" is "Red" or "fieldB" is "Blue". By adding a field "fieldA_is_Red_or_fieldB_is_Blue", you could then perform a single query on that field. This may seem horribly contrived in this example, but in many use-cases it is more reasonable and may be a good way to implement your OR use-case with a single query.

CodePudding user response:

You could just create a complex where

Take a look at the where property in https://www.npmjs.com/package/firebase-firestore-helper

Disclaimer: I am the creator of this library. It helps to manipulate objects in Firebase Firestore (and adds Cache)

Enjoy!

  • Related