Reputation: 2337
I'm looking for a way to sort Firestore query results that use arrayContainsAny
or in
for the whereField
clause.
Every time I set up a paginated query and process the first batch, I get different results back in different order.
The Firestore documentation says
You cannot order your query by any field included in an equality (=) or in clause.
I've tried ordering by name
field and first ordering by categories
and then other fields.
Whatever I enter does not seem to be used for the query.
Let's imagine the following data structure:
brands/
chiquita/
products/
banana: {
name: "Banana",
categories: ["fruits", "berries"]
}
365organic/
products/
romaine: {
name: "Romaine Lettuce",
categories: ["lettuce", "vegetables"]
}
mars/
products/
snickers: {
name: "Snickers",
categories: ["chocolate bars"]
}
Here's my Firestore query in swift:
var query = self.database.collectionGroup("products")
.whereField("categories", arrayContainsAny: ["fruits", "vegetables"])
.orderBy("name")
.limit(to: 25)
// lastSnapshot is the last doc's snapshot or nil if called the first time
if let lastSnapshot = lastSnapshot {
query = query.start(afterDocument: lastSnapshot)
}
Upvotes: 0
Views: 313
Reputation: 2337
After digging deeper through the client logic I found an issue that caused the sorting to not be applied client-side.
After fixing that I'm getting back the items sorted consistently!
Upvotes: 1