Firestore Pagination (Python)

April 24, 2019
Loop query documents with limit and paging
limit = 10
query = db.collection("test") \
    .where("is_active", '==', True) \
    .order_by("created", direction=firestore.Query.DESCENDING) \
    .limit(limit)

docs = query.stream()
count = 0

while True:
    # docs is an iterator, not list
    # docs = list(docs)
    # last_doc = docs[-1]
    # size = len(docs)}

    doc = None
    current_count = 0
    for doc in docs:
        current_count += 1
        logging.info(f"{doc.id}, {doc.get('content')}")

    last_doc = doc
    count += current_count

    if not last_doc or current_count < limit:
        break

    logging.info("next_page")
    docs = query.start_after(last_doc).get()

logging.info(f"count={count}")

NOTE: For paging to work, query must include order_by.

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.