2017-10-17 37 views
2

我想實現多個查詢和分頁與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或我的結局有關。

回答

1

在firebase上有關於Pagination & Queryquery data的文檔。我們必須使用startAt()startAfter()方法來定義一個查詢的起點。同樣,使用ENDAT()endBefore()方法來定義終點爲您的查詢結果。

舉例: 要獲得所有城市,人口> = 100萬,人口有序,

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

,並獲得一個人口< = 100萬,人口下令所有城市,

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

Firestore查詢只能有一個範圍條件。

documentation on queries

您可以orderBy()limit()結合where()過濾器。

但是,如果你有一個範圍比較(<<=>>=)過濾器,你的第一順序必須是在同一個領域:

無效:範圍過濾器,並在不同的第一排序依據田

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

所以我不能結合範圍比較(<, <=, >,> =)與startAfter不同的屬性? 有沒有解決它的方法? – haim

0

弗蘭克指出,到目前爲止,公司的FireStore不允許在不同的屬性組合範圍。我希望谷歌有一天能解決這個問題,有多個範圍過濾器似乎是任何數據庫的一個非常重要的功能。

這也是一個相當難看的解決方案,但我想你可以省略.where('price', '>=', 2)部分,然後在客戶端過濾掉數據。

+0

謝謝你給我的想法。我將它從範圍更改爲大。我猜它總比沒有好。我真的不明白他們爲什麼不實現像mongo這樣的所有功能。它真的很難與它合作。 – haim

+0

@shimonhatoka他們會妥善做到這一點在未來...他們增加了很多新的功能,因爲我是從去年開始使用它:) –