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

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

DDD
DDD原創
2024-10-28 12:51:30763瀏覽

 How to Effectively Delete Collections and Subcollections in Firestore?

刪除 Firestore 中的集合和子集合

使用 Firestore 時,可能會出現需要刪除集合或子集合的情況。然而,刪除包含子集合的父文檔會帶來挑戰。本文討論如何有效地管理此類情況。

資料庫結構和刪除問題

考慮一個名為「清單」的集合的場景,其中每個文件代表一個清單及其唯一的 ID。每個清單文件都有名為「employees」和「locations」的子集合。結構如下:

(lists)
    -listId
       (employees)
       (locations)

如果用戶希望刪除特定列表,刪除「listId」文件將保留其子集合,這違背了 Firestore 的文件。

解決方案:順序刪除

為了解決這個問題,我們提出了一種順序刪除方法:

  1. 檢索“employees”子集合中的所有文件並刪除它們。
  2. 對「locations」子集合重複此程序。
  3. 最後,刪除「listId」文件。

此方法可確保完全刪除特定清單及其關聯的子集合。

注意事項

雖然刪除是一種有效的工具,但 Firebase 建議謹慎使用它,尤其是對於大型集合。然而,對於較小的集合,刪除是一個可行的選擇。如果對大型集合使用刪除是不可避免的,請在受信任的伺服器環境中執行。

Android 程式碼實作

對於Android 應用程序,您可以使用以下程式碼實作刪除過程:

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();
}

此程式碼批次擷取和刪除文檔,確保刪除集合及其子集合。

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

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