【问题标题】:How to delete multiple documents from Cloud Firestore?如何从 Cloud Firestore 中删除多个文档?
【发布时间】:2018-06-18 21:41:46
【问题描述】:

从 Cloud Firestore 中删除许多(不是全部)文档的最佳方法是什么?

官方文档包含有关删除一个文档和所有文档的信息:https://firebase.google.com/docs/firestore/manage-data/delete-data。

【问题讨论】:

  • 你是如何衡量效率的?
  • 尚未测量,但执行一个查询是否比执行许多(例如 100 个)查询更有效?
  • 删除不是查询。在您有证据证实您的主张之前,我认为 Stack Overflow 无法为您做任何事情。不要对客户端 SDK 的工作方式做出假设。
  • 也许我问错了问题。应该是:从 Cloud Firestore 中删除许多(不是全部)文档的最佳方法是什么?
  • 您提供的 API 允许您单独删除文档。

标签: firebase google-cloud-firestore


【解决方案1】:
FirebaseFirestore db = FirebaseFirestore.getInstance();

WriteBatch writeBatch = db.batch();

for (int i=0;i<cartList.size();i++){
    DocumentReference documentReference = db.collection("Users").document(cartList.get(i).getProductId());
    writeBatch.delete(documentReference);
}

writeBatch.commit().addOnSuccessListener(new OnSuccessListener<Void>() {
    @Override
    public void onSuccess(Void aVoid) {
        // Do anything here
    }
});

【讨论】:

    【解决方案2】:

    我为此使用了批量写入。例如,我删除了所有“文本”字段为空的文档:

    const emptyMessages = await firestore.collection('messages').where("text", "==", "").get()
    const batch = firestore.batch();
    emptyMessages.forEach(doc => {
        batch.delete(doc.ref);
    });
    await batch.commit();
    

    【讨论】:

      【解决方案3】:
      btnDeleteSomeTasks.setOnClickListener{
          for (ids in 0 until mRecyclerView.size){
              val currentID = entryAdapter.snapshots.getSnapshot(ids).id
              val reference = firestore.collection("allTasks")
                  .document(user.uid)
                  .collection("userTasks")
                  .document(currentID)
              reference.delete()
              notifyItemRemoved(ids)
          }
      }
      

      【讨论】:

        【解决方案4】:

        由于这是您搜索“如何删除 Firestore 上的多个文档”时的第一个结果,我想分享一个工作代码 sn-p,它不仅可以满足 OP 的要求,而且还将您的批次拆分为块以避免达到500 commits per batch 的限制。

        const deleteEmptyMessages = async () => {
          
          const snapshot = await firestore.collection('messages').where('text', '==', '').get();
          const MAX_WRITES_PER_BATCH = 500; /** https://cloud.google.com/firestore/quotas#writes_and_transactions */
        
          /**
           * `chunk` function splits the array into chunks up to the provided length.
           * You can get it from either:
           * - [Underscore.js](https://underscorejs.org/#chunk)
           * - [lodash](https://lodash.com/docs/4.17.15#chunk)
           * - Or one of [these answers](https://stackoverflow.com/questions/8495687/split-array-into-chunks#comment84212474_8495740)
           */
          const batches = chunk(snapshot.docs, MAX_WRITES_PER_BATCH);
          const commitBatchPromises = [];
        
          batches.forEach(batch => {
            const writeBatch = firestore.batch();
            batch.forEach(doc => writeBatch.delete(doc.ref));
            commitBatchPromises.push(writeBatch.commit());
          });
        
          await Promise.all(commitBatchPromises);
        };
        

        【讨论】:

          【解决方案5】:

          要删除多个文档,您可以执行单个batched write。 WriteBatch class has a delete() method 用于此目的。

          我希望单个BatchedWrite 和多个DocumentReference.delete 调用之间的性能非常相似。如:我希望它们对于用户选择要删除的文档的情况都足够有效。如果您发现情况并非如此,请分享重现性能问题的代码。

          【讨论】:

          • 嗨弗兰克,感谢您的回答,但我已经优化了我的代码并且单独删除文档就足够了。
          猜你喜欢
          • 2021-10-16
          • 2020-12-11
          • 2019-02-15
          • 2021-03-16
          • 1970-01-01
          • 2021-01-07
          • 1970-01-01
          • 2021-03-09
          • 2018-03-22
          相关资源
          最近更新 更多