首頁  >  文章  >  Java  >  如何有效刪除Firestore集合和子集合?

如何有效刪除Firestore集合和子集合?

Barbara Streisand
Barbara Streisand原創
2024-10-26 15:30:03454瀏覽

How to Delete Firestore Collections and Subcollections Effectively?

刪除Firestore 中的集合和子集合

問題陳述:

問題陳述:

問題陳述:建議的解決方案:
  • 1.迭代刪除子集合:
  • 檢索員工和位置子集合中的所有文件。

刪除每個檢索到的文件。 刪除清單文件。

  • 2.使用deleteCollection方法(不建議):
  • Firestore的deleteCollection方法會遞歸刪除集合中的所有文件。

僅對小型集合使用此方法以避免記憶體錯誤.確保從受信任的伺服器環境執行此操作。

<code class="java">private void deleteCollection(final CollectionReference collection, Executor executor) {
    Tasks.call(executor, () -> {
        int batchSize = 10;
        Query query = collection.orderBy(FieldPath.documentId()).limit(batchSize);
        List<DocumentSnapshot> deleted = deleteQueryBatch(query);

        while (deleted.size() >= batchSize) {
            DocumentSnapshot last = deleted.get(deleted.size() - 1);
            query = collection.orderBy(FieldPath.documentId()).startAfter(last.getId()).limit(batchSize);

            deleted = deleteQueryBatch(query);
        }

        return null;
    });
}

@WorkerThread
private List<DocumentSnapshot> deleteQueryBatch(final Query query) throws Exception {
    QuerySnapshot querySnapshot = Tasks.await(query.get());

    WriteBatch batch = query.getFirestore().batch();
    for (DocumentSnapshot snapshot : querySnapshot) {
        batch.delete(snapshot.getReference());
    }
    Tasks.await(batch.commit());

    return querySnapshot.getDocuments();
}</code>
用於遞歸刪除的 Android 程式碼:以下 Android 程式碼示範如何遞迴刪除集合:

以上是如何有效刪除Firestore集合和子集合?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn