'How to make a complex query to the firebase in flutter
My firestore-firebase database looks like:
products -> collection Name
| uid1 -> Document id
| price : "200"
| category: "a"
| uid2 -> Document id
| price : "500"
| category: "b"
| uid3 -> Document id
| price : "400"
| category: "b"
Now i want to get products ranging from 200 to 400
and with category b
,
I should get the product uid3
Now the values which are required are taken from the filter screen ui, which has price range slider and then it even has 6-8 categories, My interpretation of trying was creating field for each of the category and then querying, But i dont think so this is a good approach,
Because i'll have to write search query for all permutation combination of the category toggle for example if categoryA is true , categoryB is false, categoryC is true,
Then i'll have to write for all the category's fetching from the firebase,
if categoryA is true
...
where('categoryA',isEqualto:"true").get();
if categoryB is true
...
where('categoryB',isEqualto:'false').get();
...
...
...
if categoryA is true categoryB is false categoryC is true
...
where('categoryA',isEqualto:"true")
.where('categoryC', isEqualto:"true).get();
and so on and so forth which is obviosly not recommended.
how to overcome this approach and how to query such a requirement
Example Scenario
variable i have is :
minPrice : String,
maxPrice : String,
categoryA : bool,
categoryB : bool
For the given example value of attributes are :
minPrice : "200",
maxPrice : "400",
categoryA : false,
categoryB : true,
I want a Future result , How to write such a query in firebase ?
And which fields should be indexed in firebase for the effective search ?
Thank you in advance !!
Edit:
This is the fucntion which i tried just for the price, Don't know how to do for the category.
Future<List<ProductModel>> getFilteredProducts(String maxPrice, String minPrice) => FirebaseFirestore.instance
.collection("products")
.where("price", isLessThanOrEqualTo: maxPrice)
.where("price", isGreaterThanOrEqualTo: minPrice)
.get()
.then((value) => value.docs.map((e) => ProductModel.fromMap(e.data(), e.id)).toList());
Solution 1:[1]
Check here for Information about where
query
Note: this is just a sample
await FirebaseFirestore.collection('products'),
.where('price', greaterThanorEqualto: searchText)
.where(categoryB, Equalto: true)
.get()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |