Firestore pagination - how to find if there are more data after query (using limit)
我们在当前的python 2.7标准环境中使用ndb数据存储。我们将此应用程序迁移到具有Firestore(本机模式)的python 3.7标准环境。
我们在ndb数据存储上使用分页,并使用fetch构造查询。
1 | query_results , next_curs, more_flag = query_structure.fetch_page(10) |
next_curs和more_flag在指示当前查询之后(要获取10个元素)是否有更多数据要获取时非常有用。我们使用它来标记"下一页" /"上一页"的前端。
我们在Firestore中找不到与之等效的内容。有人可以帮助实现这一目标吗?
Firestore分页中没有直接等效项。相反,您可以做的是获取比该页面所需的N个文档多的一个文档,然后使用N 1个文档的存在来确定是否存在"更多"。您将在显示的页面中省略N 1文档,然后从该N 1文档开始下一页。
我不久前建立了一个自定义的firestore API,以通过分页获取记录。您可以查看存储库。这是我经历的学习周期的故事:
我的第一个尝试是使用限制和偏移量,这似乎很吸引人,但是后来我遇到了一个问题,即获取20万条记录的成本很高。因为使用偏移量时,Google还会向您收取之前所有记录的读取费用。 Google Firestore定价页面明确声明了以下内容:
There are no additional costs for using cursors, page tokens, and
limits. In fact, these features can help you save money by reading
only the documents that you actually need.However, when you send a query that includes an offset, you are
charged a read for each skipped document. For example, if your query
uses an offset of 10, and the query returns 1 document, you are
charged for 11 reads. Because of this additional cost, you should use
cursors instead of offsets whenever possible.
我的第二次尝试是使用光标最小化这些读取。我最终获取了N 1个文档,并按如下所示放置了光标:
1 2 3 4 5 6 | collection = 'my-collection' cursor = 'we3adoipjcjweoijfec93r04' # N+1th doc id q = db.collection(collection) snapshot = db.collection(collection).document(cursor).get() q = q.start_at(snapshot) # Place cursor at this document docs = q.stream() |
Google在Firestore中撰写了有关分页的整个页面。实现分页时一些有用的查询方法:
-
limit() 将查询限制为一组固定的文档。 -
start_at() 包含光标文档。 -
start_after() 在光标文档之后立即开始。 -
order_by() 确保所有文档均按特定字段排序。