使用firestore进行多查询和分页

时间:2017-10-17 05:01:21

标签: firebase google-cloud-firestore

我正在尝试使用firestore实现多查询和分页,但是一旦我添加<或者>查询光标不工作。

//working example:
the doc id i save as propery on the doc
ref.where('category','==' 'cats').where('status', '==', 1).orderBy('id').cursor('last doc id from the returned list').limit(3)

//not working exmple:

ref.where('category','==' 'cats').where('status', '==', 1).orderBy('price').where('price', '>=', 2).where('price', '<=', 55).orderBy('id').cursor('last doc id from the returned list').limit(3)

没有错误返回。是firestore还是我的错误。

4 个答案:

答案 0 :(得分:5)

Firestore查询只能有一个范围条件。

来自documentation on queries

  

您可以将where()过滤器与orderBy()limit()结合使用。

     

但是,如果您的过滤器具有范围比较(<<=>>=),则您的第一个排序必须位于同一字段中:

     

无效:范围过滤器和不同字段的第一个订单

citiesRef.where("population", ">", 100000).orderBy("country")

答案 1 :(得分:5)

Pagination & Queryquery data上的firebase上有文档。我们必须使用 startAt() startAfter()方法来定义查询的起点。同样,使用 endAt() endBefore()方法为查询结果定义终点。

实施例: 要获得按人口排序的人口数> = 1,000,000的所有城市,

db.collection("cities")
        .orderBy("population")
        .startAt(1000000);

并获得人口<= 1,000,000的所有城市,按人口排序,

db.collection("cities")
        .orderBy("population")
        .endAt(1000000);

因此应使用此方法进行分页,例如

// Construct query for first 25 cities, ordered by population
Query first = db.collection("cities")
        .orderBy("population")
        .limit(25);

first.get()
    .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot documentSnapshots) {
            // ...

            // Get the last visible document
            DocumentSnapshot lastVisible = documentSnapshots.getDocuments()
                    .get(documentSnapshots.size() -1);

            // Construct a new query starting at this document,
            // get the next 25 cities.
            Query next = db.collection("cities")
                    .orderBy("population")
                    .startAfter(lastVisible)
                    .limit(25);

            // Use the query for pagination
            // ...
        }
    });

答案 2 :(得分:1)

弗兰克指出,到目前为止,火库并不允许在不同的属性上组合范围。我希望谷歌有一天会解决这个问题,对于任何数据库来说,多个范围过滤器似乎都是非常必要的功能。

这也是一个相当丑陋的解决方案,但我想你可以省略.where('price', '>=', 2)部分,然后在客户端上过滤掉数据。

答案 3 :(得分:1)

使用FireStore和带有分页功能的Angular 8应用检查this示例应用

enter image description here

使用查询

limit()

orderBy()

startAt()

endBefore()

startAfter()

相关问题