How can I create indexes for different combinations of fields in Firestore?

Viewed 4598

Suppose I have a users collection that I want to filter in a page of mine. The fields to be filtered on are name, age, location.

For this reason, I create a composite index (name, age, location). The issue is that I want to have the opportunity to filter by any combination of the 3 - name and age, name and location, age and location. When I try to do this, I am prompted to create another composite index for the used combination of fields.

My question is - does that mean that I have to add indexes for all possible composite combinations? If yes, how can I make this happen, if I want to potentially filter by 10 fields, and not only 3? Do I have to create indexes for all combinations myself?

2 Answers

If you are using multiple equality (==) clauses for queries, then you can take advantage of index merging. Cloud Firestore can re-use existing indexes. In your case you have 3 columns name, age, and location and you want to order by hearts, then create three indexes like this:

Collection   Fields indexed
users        ↑ name,      ↑ hearts
users        ↑ age,       ↑ hearts
users        ↑ location,  ↑ hearts

Now you can create different queries with combination of name, age and location using multiple equality (==) clauses.

You can refer to the Firestore documentation about index merging here

Yes, you will have to create each combination yourself. The easiest thing to do might be to use the Firebase CLI to deploy indexes based on a JSON file you create and manage (and possibly store in source control). You could even write some code to generate this file so you don't have to manually create each combination.

Related