MeetTitan
MeetTitan

Reputation: 3568

Deleting multiple blobs from Google Cloud Storage efficiently

Deleting multiple blobs in a container is very slow when doing so one by one if the bucket contains a large amount of items.

public static void rmAll(Storage storage, String bucket) {
    Page<Blob> blobs = storage.list(bucket, Storage.BlobListOption.currentDirectory());
    for(Blob blob : blobs.iterateAll()) {
        blob.delete();
    }
}

Upvotes: 1

Views: 949

Answers (1)

MeetTitan
MeetTitan

Reputation: 3568

We can simply leverage com.google.cloud.storage.StorageBatch to efficiently delete multiple blobs in a bucket.

public static rmAll(Storage storage, String bucket) {
    StorageBatch batch = storage.batch();
    Page<Blob> blobs = storage.list(bucket, Storage.BlobListOption.currentDirectory());
    for(Blob blob : blobs.iterateAll()) {
        batch.delete(blob.getBlobId());
    }
    batch.submit();
}

Upvotes: 3

Related Questions