I am building a website that uses pagination and filtering of some data.
if (eventType) query = query.where('general.eventType', '==', eventType);
if (price) query = query.where('general.eventTicketPrice', price == "free" ? '==' : '>=', 0);
if (startDate) query = query.where('general.eventDates.start', '>=', new Date(startDate));
if (endDate) query = query.where('general.eventDates.start', '<=', new Date(endDate));
if (location) query = query.where('general.location.city', '==', location);
if (participation) query = query.where('general.locationType', '==', participation);
...
...
I have about 20 filters that I use, and whenever I select any filter the firebase needs me to create a new index. I am assuming that I need to do this for each combination of filters. I basically made a combination generator that tries each query and gives me the URL for creating the index, but there are A LOT of them. Like thousands so naturally I don’t want to generate them manually.
Is there a way to fix this issue?
I thought about getting all the documents and then filtering manually. It would be easy to implement but may be costly and maybe high latency (idk). Currently, there are not many documents but I want to be able to query hundreds maybe thousands of documents.
What are some recommendations for this type of issue?
2
Answers
A general rule for Firestore is that it every query is always executed against one or more indexes, but that doesn’t mean you need a separate index for every query. From the documentation on index merging:
In your case, you might need to move your relational conditions (
>=
,<=
, etc) to the end of the query, but could then potentially depend on the existing single field indexes for most equality checks.Note: queries that use merged indexes will typically perform slower than if you’d create a dedicated composite index for them. So you’ll want to keep an eye on query performance, and optimize as needed.
I actually recorded a short video about an instance where this happened during Google I/O last year, which you can see here.
Not clear on what is broken in your case, but generally speaking:
https://firebase.google.com/docs/firestore/query-data/indexing
Then at https://firebase.google.com/docs/firestore/query-data/queries#query_limitations …