Error using orderBy and startAfterDocument in a query

Viewed 1021

When using orderBy and startAfterDocument in the same query, I get the following error:

failed: Status{code=FAILED_PRECONDITION, description=The query requires an index. You can create it here: https://console.firebase.goog...

This error is being caught when I try to receive the next set of documents. Tried to create an index using the link provided in the error but it's a single index using the 'finalTimeStamp' field is being generated and firestore throws out the following exception.

this index is not necessary, configure using single field index controls

In my single field indexes, the descending index for a collection scope is already enabled.

My code:

    if (_lastVisible == null) {
      try {
        data = await chatList
            .document(widget.currentUserId)
            .collection('inbox')
            .orderBy('finalTimeStamp', descending: true)
            .limit(10)
            .getDocuments();
      } catch (e) {
        print('caught error 1');
      }
    } else {
      try {
        data = await chatList
            .document(widget.currentUserId)
            .collection('inbox')
            .orderBy('finalTimeStamp', descending: true)
            .startAfterDocument(_lastVisible)
            .limit(10)
            .getDocuments();
      } catch (e) {
        print('caught error 2');
      }
    }
1 Answers

The orderBy and startAfter or startAfterDocuments should be performed on the same field.

In my question above I've performed orderBy on the finalTimeStamp field and was using startAfterDocument which considers the document ID while ordering the documents. Hence, firestore throws an error.

You can solve this issue in 2 ways:

  1. You can perform startAfter() on finalTimeStamp field. (Didn't consider this for my case because I though there may be multiple documents with the same finalTimeStamp. Using this could give out wrong results)

  2. I created a chatRef field in my documents referencing the same document. I then created an index in firestore to order my documents by finalTimeStamp first and chatRef later. Now while querying, I performed orderBy() twice on finalTimeStamp and chatRef along with the startAfterDocument().

Related