Home > Software engineering >  Why are there two index-entries for each item for array-contains in Firestore?
Why are there two index-entries for each item for array-contains in Firestore?

Time:01-15

As per the documentation, there are 2 single-field index entries (ASC and DESC) for array-contains for each of the items in the neighborhoods array:

Index Indexed Data
... ...
neighborhoods Array Contains ASC neighborhoods: "Mission"
neighborhoods Array Contains DESC neighborhoods: "Mission"
neighborhoods Array Contains ASC neighborhoods: "Downtown"
neighborhoods Array Contains DESC neighborhoods: "Downtown"
neighborhoods Array Contains ASC neighborhoods: "Marina"
neighborhoods Array Contains DESC neighborhoods: "Marina"

The documentation also says that:

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

It also shows only a single index mode for array-contains here.

The first link seems to contradict the last two. What am I missing? Why are there two entries for each item in the single-field index entries?

CodePudding user response:

Someone from the Firebase team will have to confirm, but to my understanding there are two array-contains indexes due to the ordering of the __name__ field of each document - one where __name__ is sorted in ascending order and the other where it is sorted in descending order.

The indexing of the __name__ field is covered in the documentation here where it states:

By default, the __name__ field is sorted in the same direction of the last sorted field in the index definition. To sort results by the non-default __name__ direction, you need to create that index.

As an array-contains filter doesn't have an explicit direction, the entries in its results need to be indexed in both directions for when you sort the results by the document ID (documentId()) which uses __name__ under the hood.

  • Related