multiple where query in firestore queryBuilder

可紊 提交于 2021-02-05 07:49:26

问题


I just noticed today that whenever I want to query a database I get an error which doesn't really make a sense to me and querying just stop working. It worked just fine few weeks ago.

Invalid Query. All where filters with an inequality (lessThan, lessThanOrEqual, greaterThan, or greaterThanOrEqual) must be on the same field. But you have inequality filters on 'value1' and 'value2')

  Stream<List<MyModel>> myStream(
      {MyFilter filter, String category}) {
    return _service.collectionsStream(
        path: APIPath.tools(cid, category),
        queryBuilder: filter != null
            ? (query) => query
                .where('value1', isGreaterThan: filter.minValue1)
                .where('value1', isLessThan: filter.maxValue1)
                .where('value2', isLessThan: filter.maxValue2)
                .where('value2', isGreaterThan: filter.minValue2)
            : null,
        builder: (data, documentID) => MyModel.fromMap(data, documentID),
        sort: (lhs, rhs) => lhs.value1.compareTo(rhs.value1));
  }

Am I doing something wrong? What does that error means and why I didn't get it last time?


回答1:


A Firestore query can only contain relational conditions (>, <, etc) on a single field. From the documentation on query limitations:

Queries with range filters on different fields are not supported.

So you'll have to choose which field you want Firestore to perform a range filter on. You'll then have to do the others in your application code.

To learn more about why this limit exists, and on working within Firestore's limitations to implement use-cases, I highly recommend checking out the video series Getting to know Cloud Firestore.




回答2:


With firebase you can't do a query on multiples fields of a document. So in your case you can't do a query on 'value1' AND 'value2', you have to do a query on 'value1' and after, filter in intern your query to match 'value2'.

Example:

//your query code 
queryBuilder: filter != null
            ? (query) => query             
                .where('value2', isGreaterThan: filter.minValue2)
                .where('value2', isLessThan: filter.maxValue2)
                ...
            : null,
//your query code

myQuery = querySnapshot.documents.where((document) => document.data['value1'] > filter.minValue1).toList();


来源:https://stackoverflow.com/questions/61306009/multiple-where-query-in-firestore-querybuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!