0

I just little modified official sample snippet like below

    static void deleteCollection(CollectionReference collection, int batchSize) {
    try {
        // retrieve a small batch of documents to avoid out-of-memory errors
        ApiFuture<QuerySnapshot> future = collection.limit(batchSize).get();
        int deleted = 0;
        // future.get() blocks on document retrieval
        List<QueryDocumentSnapshot> documents = future.get().getDocuments();
        for (QueryDocumentSnapshot document : documents) {

            //delete subcollections
            Iterable<CollectionReference> collections =
                    document.getReference().listCollections();
            for (CollectionReference collRef : collections) {
                deleteCollection(collRef, batchSize);
            }
            //delete document
            document.getReference().delete();
            ++deleted;
        }
        if (deleted >= batchSize) {
            // retrieve and delete another batch
            deleteCollection(collection, batchSize);
        }
    } catch (Exception e) {
        System.err.println("Error deleting collection : " + e.getMessage());
    }
}

But this code does not work for me. Document subcollections remain as it. What is wrong here? Thank you your answer

garawaa garawaa
  • 154
  • 1
  • 6

2 Answers2

0

Just sharing for someone correct code

private static void deleteCollection(CollectionReference collection, int batchSize) {
    try {
        // retrieve a small batch of documents to avoid out-of-memory errors
        ApiFuture<QuerySnapshot> future = collection.limit(batchSize).get();
        int deleted = 0;
        // future.get() blocks on document retrieval
        List<QueryDocumentSnapshot> documents = future.get().getDocuments();
        for (QueryDocumentSnapshot document : documents) {

            //delete document
            document.getReference().delete();
            ++deleted;
            //delete subcollections
            Iterable<CollectionReference> collections =
                    document.getReference().listCollections();
            for (CollectionReference collRef : collections) {
                deleteCollection(collRef, batchSize);
            }

        }
        if (deleted >= batchSize) {
            // retrieve and delete another batch
            deleteCollection(collection, batchSize);
        }
    } catch (Exception e) {
        System.err.println("Error deleting collection : " + e.getMessage());
    }
}
garawaa garawaa
  • 154
  • 1
  • 6
-1

Put the below before for loop: document.getReference().delete(); ++deleted;