While I'm using the below query in Firestore, an error is coming:
Code:
query = database.collection("CustomerViews/Data/Post")
.whereGreaterThanOrEqualTo("postDate", startDate)
.whereLessThanOrEqualTo("postDate", endDate)
.orderBy("postViews", Query.Direction.DESCENDING)
.orderBy("postDate", Query.Direction.DESCENDING)
Error:
Invalid query. You have an inequality where filter (whereLessThan(), whereGreaterThan(), etc.) on field 'postDate'
and so you must also have 'postDate' as your first orderBy() field, but your first orderBy() is currently on field
'postViews' instead.
CodePudding user response:
The error message is quite explicit about the error. You are using both "whereGreaterThan()" and "whereLessThan()" on the "postDate" field, but you aren't first ordering the results based on that field, hence that error. Please remember, that the order of the method calls in Firestore is very important. To solve this, please change your query to:
query = database.collection("CustomerViews/Data/Post")
.orderBy("postDate", Query.Direction.DESCENDING)
.whereGreaterThanOrEqualTo("postDate", startDate)
.whereLessThanOrEqualTo("postDate", endDate)
.orderBy("postViews", Query.Direction.DESCENDING)
And right after that, simply create the corresponding index. That's it.
CodePudding user response:
Based on your sample code, you have an inequality wherein postDate
should be initialized first before postViews
as the error suggested. This is currently a restriction of orderBy()
clause wherein your first ordering must be on the same field.
In addition to @Alex's answer, You may check the links below for similar scenarios
- Firestore query order on field with filter on a different field
- Firestore "Invalid query" - Am I using Indexing wrong?
Finally, here's a documentation for the limitations of order and limit data with Cloud Firestore.