multi query and pagination with firestore

后端 未结 4 947
自闭症患者
自闭症患者 2021-01-02 11:31

I am trying to implement multi query and pagination with firestore, but once I add < or > to the query the cursor not working.



        
4条回答
  •  [愿得一人]
    2021-01-02 11:46

    There has documentation at firebase on Pagination & Query and query data. We have to use the startAt() or startAfter() methods to define the start point for a query. Similarly, use the endAt() or endBefore() methods to define an end point for your query results.

    Example: To get all cities with a population >= 1,000,000, ordered by population,

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

    and to get all cities with a population <= 1,000,000, ordered by population,

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

    So pagination should be done using this method like,

    // Construct query for first 25 cities, ordered by population
    Query first = db.collection("cities")
            .orderBy("population")
            .limit(25);
    
    first.get()
        .addOnSuccessListener(new OnSuccessListener() {
            @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
                // ...
            }
        });
    

提交回复
热议问题