Lukas Petersson
Lukas Petersson

Reputation: 315

Firestore "Invalid query" - Am I using Indexing wrong?

I am building an app with a firebase cloud firestore datadabse with the following structure:enter image description here

I am doing a query of a user´s books where the field "StartDate" is greater than 0 and the "EndDate" is equal to 0, that query should then be ordered by Title.

CollectionReference booksCollection = mFirebaseDatabase.collection("users").document(user.getUid()).collection("books");

Query databaseQuery = booksCollection.whereGreaterThan("StartDate", 0).whereEqualTo("EndDate", 0).orderBy("Title");

databaseQuery.get()

To do this i read that you need to use indexing (although i did not get a link to indexing in errormessages as it stated that I should). my indexing looks like this:

enter image description here

but i get the errormessage:

java.lang.IllegalArgumentException: Invalid query. You have an inequality where filter (whereLessThan(), whereGreaterThan(), etc.) on field 'StartDate' and so you must also have 'StartDate' as your first orderBy() field, but your first orderBy() is currently on field 'Title' instead.

Upvotes: 7

Views: 7830

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599716

Firestore queries can only sort or filter range on a single field. You're trying to filter on StartDate and then order on Title, which isn't possible.

The Firestore documentation on queries contains this similar example of a query that isn't allowed:

Invalid: Range filter and first orderBy on different fields

citiesRef.whereGreaterThan("population", 100000).orderBy("country");

Firestore only allows queries where it can meet its performance guarantees, and for ordering/range-filtering on multiple fields that is not (currently) possible. See Todd's video on Firestore queries to learn more on how this works.

The typical workaround is to let Firestore handle the filter (on StartDate in your case, and then reorder the results in the Android app.

Upvotes: 10

Related Questions