简体   繁体   中英

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());

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM