简体   繁体   English

Firestore:缓存和读取数据

[英]Firestore: caching and reading data

I have a flutter app running the following query:我有一个 flutter 应用程序运行以下查询:

Future<QuerySnapshot<Object?>> getPendingDiscoveryChats(
      String userId, DocumentSnapshot? lastDocument) async {
    QuerySnapshot result;
    if (lastDocument == null) {
      result = await FirebaseFirestore.instance
          .collection('discoveryChats')
          .where('senderId', isEqualTo: userId)
          .where('pending', isEqualTo: true)
          .orderBy('lastMessageSentDateTime', descending: true)
          .limit(10)
          .get();
    } else {
      result = await FirebaseFirestore.instance
          .collection('discoveryChats')
          .where('senderId', isEqualTo: userId)
          .where('pending', isEqualTo: true)
          .orderBy('lastMessageSentDateTime', descending: true)
          .startAfterDocument(lastDocument)
          .limit(10)
          .get();
    }
    return result;
  }

This gets me a list of chats.这让我得到了一个聊天列表。 This query is first ran when the screen is loaded, but there is a refresh indicator aswell to call for updates.此查询在加载屏幕时首先运行,但还有一个刷新指示器来调用更新。 So my question is this: say there is the case where ten documents are loaded, and a new one is added.所以我的问题是:假设有十个文档被加载的情况,然后添加了一个新文档。 When the refresh occurs, the query gets 1 new document, and 9 unchanged ones.刷新发生时,查询获得 1 个新文档和 9 个未更改的文档。 Did the 9 unchanged documents come from the cache, or did they cost me reads?这 9 个未更改的文档是来自缓存,还是耗费了我的读取时间?

And another case is where the refresh occurs when no changes happens.另一种情况是在没有发生任何变化时发生刷新。 Does Firestore charge me 10 reads to confirm the results are all the same values? Firestore 是否会向我收取 10 次读取以确认结果都是相同的值?

Thank you!谢谢!

Anytime there is a refresh and get() is called, you are charged for 10 reads because that is what get() returned for the query.任何时候刷新并调用 get() 时,您都需要为 10 次读取付费,因为这是 get() 为查询返回的内容。 It is irrelevant that they are in cache because, as you said, there were still reads to confirm the values are the same.它们在缓存中是无关紧要的,因为正如您所说,仍然存在读取以确认值相同。

I would recommend you make use of Streams to allow for instant updating anytime something in the query changes without the user needing to refresh.我建议您使用 Streams 允许在查询中的任何内容发生变化时即时更新,而无需用户刷新。 This is also more read efficient and is best practice.这也提高了读取效率,是最佳实践。 Below is the example from the documentation以下是文档中的示例

Stream collectionStream = FirebaseFirestore.instance.collection('users').snapshots();
Stream documentStream = FirebaseFirestore.instance.collection('users').doc('ABC123').snapshots();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM