Jonathan
Jonathan

Reputation: 9151

Firestore multiple orderBy (composite index) can't find some results

I have a query that I run over multiple data types. One of the collections stopped returning results after I added orderBys.

getEntitiesOfType(entityType: EntityType): Observable<StructuralEntity[]> {
    const collection = this.findCollection(entityType);

    const entities$ = this.afs
      .collection(collection, (ref) =>
        ref.orderBy('disabled').orderBy('title').orderBy('id') // Here is the issue
      )
      .snapshotChanges()
      .pipe(
        map((docs) =>
          docs.map((dca) => {
            const data = dca.payload.doc.data() as StructuralEntity;
            return {
              id: dca.payload.doc.id,
              title: data.title,
              name: data.name,
              type: data.type,
              icon: data.icon,
              model: data.model,
              context: data.context,
              disabled: data.disabled,
            } as StructuralEntity;
          })
        )
      );

    return entities$;
  }

I had to order some collection by disabled and title, the collection that stopped returning results doesn't have those fields so I suppose that is why it doesn't return anything anymore. I've added field id to the composite index, which it certainly has, hoping it would work again. It does not.

Why does Firestore not return anything for this index?

disabled title id
undefined undefined "1"
undefined undefined "2"

Upvotes: 0

Views: 117

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

Firestore only includes documents in an index that have a value for the fields in that index.

If a document doesn't have a value for the disabled field, it won't exist in the composite index, and thus can never be returned from a query that uses that index.

If you want such documents to be returned, you'll have to add the new field to the documents with some default value.

Upvotes: 1

Related Questions