Let's say I have a collection of cars and I want to filter them by price
range and by year
range. I know that Firestore has strict limitations due performance reasons, so something like:
db.collection("products")
.where('price','>=', 70000)
.where('price','<=', 90000)
.where('year','>=', 2015)
.where('year','<=', 2018)
will throw an error:
Invalid query. All where filters with an inequality (<, <=, >, or >=) must be on the same field.
So is there any other way to perform this kind of query without local data managing? Maybe some kind of indexing or tricky data organization?
The error message and documentation are quite explicit on this: a Firestore query can only perform range filtering on a single field. Since you're trying to filter ranges on both
price
andyear
, that is not possible in a single Firestore query.There are two common ways around this:
Given the difference in effort between these two, I'd recommend picking the first option.
A third option is to model your data differently, as to make it easier to implement your use-case. The most direct implementation of this would be to put all products from 2015-2018 into a single collection. Then you could query that collection with
db.collection("products-2015-2018").where('price','>=', 70000).where('price','<=', 90000)
.A more general alternative would be to store the products in a collection for each year, and then perform 4 queries to get the results you're looking for: one of each collection
products-2015
,products-2016
,products-2017
, andproducts-2018
.I recommend reading the document on compound queries and their limitations, and watching the video on Cloud Firestore queries.