Search code examples
google-cloud-firestore

Firestore index on maps and array - clarification


I'm trying to understand how Firestore creates indexes on fields. Given the following sample document, how are indexes created, especially for the maps/arrays?

enter image description here

I read the documentation at Index types in Cloud Firestore multiple times and I'm still unsure. There it says:

Automatic indexing By default, Cloud Firestore automatically maintains single-field indexes for each field in a document and each subfield in a map. Cloud Firestore uses the following default settings for single-field indexes:

  • For each non-array and non-map field, Cloud Firestore defines two collection-scope single-field indexes, one in ascending mode and one in descending mode.

  • For each map field, Cloud Firestore creates one collection-scope ascending index and one descending index for each non-array and non-map subfield in the map.

  • For each array field in a document, Cloud Firestore creates and maintains a collection-scope array-contains index.

  • Single-field indexes with collection group scope are not maintained by default.

If I understand this correctly then there is an index created for each of these fields, even for the values in the alternate_names array.

So if I want to search for any document where fields.alternate_names contains a value of (for example) "Caofang", then Firestore would use an index for its search

Is my assumption/understanding correct?


Solution

  • No, your understanding is not correct. fields.alternate_names is an array subfield in a map field, which means it would not satisfy the requirements in the second point. You can test your assumption simply by issuing the query. If the query fails, you will see in the error message that it failed due to lack of index.

    Firestore will simply not allow queries that are not indexed. The error message from that failure will contain a link to the console that will let you create the index necessary for that query, if such a thing is possible.

    If you want to be able to query the contents of fields.alternate_names, consider promoting it to its own top-level field, which will be indexed by default.