Does Firestore require a separate index for EVERY combination of queried fields? (9 FAILED_PRECONDITION: The query requires an index.)

Viewed 62

I am trying to implement logic for querying people collections for suggestion of names based on a combination of arguments of 3 possible (name, surname, nick), eg:

people.where('name', '==', nameArg).where('surname', '>=', surnameArg).where('surname', '<=', surnameArg + '\uf8ff')

or

people.where('nick', '==', nickArg).where('name', '>=', nameArg).where('name', '<=', nameArg+ '\uf8ff')

The idea is that there might be any 1 or 2 fields using == operator and one with >= / <=. I got the error 9 FAILED_PRECONDITION: The query requires an index., so I created an index using all 3 of the fields. But when my query uses only 2 of the fields I still get the same error.

Am I expected to create 4 indices for every combination of query parameters? This feels so wrong.

Does the order of fields in the index matter too?

1 Answers

While you'll often end up with many indexes on your Firestore project, you may not need a composite index for each combination of fields. They key here is that Firestore can use the single-field indexes for equality checks.

From the documentation on taking advantage of index merging:

Although Cloud Firestore uses an index for every query, it does not necessarily require one index per query. For queries with multiple equality (==) clauses and, optionally, an orderBy clause, Cloud Firestore can re-use existing indexes. Cloud Firestore can merge the indexes for simple equality filters to build the composite indexes needed for larger equality queries.

I must admit I always struggle a bit with how to apply this on my own projects, but for example the FriendlyEats sample project uses surprisingly few indexes for the amount of sorting and filtering it allows.

Related