Does Firestore index field order matter?

Viewed 668

For one of my collections I created the following index:

  • createdOn: timestamp (Ascending)
  • ordinal: number (Ascending)
  • parent: reference (Ascending)

However, when I run a query that uses all three fields, firestore won't fetch anything and is suggesting this index instead (the last two fields are swapped):

  • createdOn: timestamp (Ascending)
  • parent: reference (Ascending)
  • ordinal: number (Ascending)

I also tried to change the order of where* and orderBy in the query but it didn't have any effect. So, now I have two indexes and don't understand why one of them isn't working and the other one is fine.

Why do I need a different index? The docs don't mention it (at least here).


The query I'm using is this one:


    private val firestore = FirebaseFirestore.getInstance()

    fun texts(languageId: String, storyId: String): Task<QuerySnapshot> {
        return firestore
            .collection("/languages/$languageId/texts")
            .whereIn("createdOn", dates) // <-- List<Timestamp>
            .whereEqualTo("parent", firestore.document("/languages/$languageId/stories/$storyId"))
            .orderBy("ordinal", Query.Direction.ASCENDING)
            .get()
    }
1 Answers

As mentioned by @MikeG in the comment, I can confirm that, the sequence for the where field is not important, but orderBy field must always be last. It is good practice to break down the index into 2 indices:

  • createdOn (Ascending), ordinal (Ascending)

  • parent (Ascending), ordinal (Ascending)

Firestore will merge them together while query, and it can save some cost and also reuse the index at different scenario.

Related