在页面加载时减少聊天应用程序中 firestore 文档读取的最佳方法是什么?

What is the best way to reduce firestore document reads in chat app on page load?

我有一个聊天应用程序,每次加载页面都会向我收取大量阅读费用,每条消息显示 1 次。我正在尝试找出一种方法来减少该数量并优化成本,因为刷新页面几次需要数百次阅读。

firestore pricing documentation

For queries other than document reads, such as a request for a list of collection IDs, you are billed for one document read. If fetching the complete set of results requires more than one request (for example, if you are using pagination), you are billed once per request.

我考虑过,如果我在不使用 here in the docs 所示的查询的情况下获取整个集合,可能会出现成本差异。我确定这可能是错误的,但我找不到任何指定仅需 1 次读取的例外情况的内容。我还想到创建一个数组来保存集合父文档中的最新消息,但是更新该数组的安全规则似乎过于复杂且不实用。我还阅读了有关使用 firebase 缓存的信息,但这在这里似乎没有用。

这是演示我当前如何加载消息的代码。我正在使用 react-firebase-hooks 库通过 useCollectionData:

对这些数据进行快照
const q = query(messagesRef, orderBy("createdAt", "desc"), limit(100))
const [messages] = useCollectionData(q)

在研究过程中,我发现 我很确定接受的答案是错误的。这确实让我质疑规则。是否有任何策略可以减少此常见用例的读取次数?

Pagination still incurs charges on a per-document read, right?

是的,但 仅当您加载更多页面时

I'm not trying to load the entire collection, but rather wondering if loading the collection without a query has a different cost than with.

在没有限制结果的查询的情况下加载集合,意味着您正在阅读整个集合。而且,是的,如果您不使用查询,成本会高得多。请记住,在 Firestore 中读取 collection/query 的成本等于实际返回的文档数。例如,如果您收集了 100 万份文档,而您的查询 returns 100,则您只需支付 100 次文档读取费用。

I'm overall trying to figure out if there's a strategy that can improve the read cost of the example query I gave.

没有。如果您需要获取最新的 100 条消息,这是您可以拥有的最佳查询。减少读取次数的唯一更改是更改传递给 limit() 函数的值。也许这是有道理的,因为用户可能对一次阅读 100 条消息不感兴趣。始终尝试显示适合屏幕的数据,并逐步加载任何其他数据。