Skip to content

Instantly share code, notes, and snippets.

@JaredEzz
Created January 24, 2023 20:39
Show Gist options
  • Save JaredEzz/6822c4f2d063e8cff942d6a8fcd91b57 to your computer and use it in GitHub Desktop.
Save JaredEzz/6822c4f2d063e8cff942d6a8fcd91b57 to your computer and use it in GitHub Desktop.
Clear all Firebase Cloud Firestore Collections
import com.google.api.core.ApiFuture;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.firestore.CollectionReference;
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.QueryDocumentSnapshot;
import com.google.cloud.firestore.QuerySnapshot;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.cloud.FirestoreClient;
import java.io.IOException;
import java.util.List;
class ClearCollections {
public static void main(String[] args) throws IOException {
final int BATCH_SIZE = 5;
Firestore firestore = initializeCloudFirestore();
for (CollectionReference listCollection : firestore.listCollections()) {
deleteCollection(listCollection, BATCH_SIZE);
}
}
/**
* One way of initializing Firestore,
* see other options at https://firebase.google.com/docs/firestore/quickstart#initialize
*/
private static Firestore initializeCloudFirestore() throws IOException {
// Use the application default credentials
GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(credentials)
.setProjectId("projectId")
.build();
FirebaseApp.initializeApp(options);
Firestore firestore = FirestoreClient.getFirestore();
return firestore;
}
/**
* Delete a collection in batches to avoid out-of-memory errors. Batch size may be tuned based on
* document size (atmost 1MB) and application requirements.
* See https://firebase.google.com/docs/firestore/manage-data/delete-data#java_5
*/
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) {
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());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment