user3324360
user3324360

Reputation: 81

Azure blob container listBlobs to fetch files with a specific extension in java

I've a java code where I list blobs and filter in for loop to fetch only files with a specific extension. Is there a way to query/request container to return just blobs with specific extension? I don't want to loop through all the blobs in the container to do this.

Upvotes: 3

Views: 3011

Answers (3)

Nitin
Nitin

Reputation: 3832

You can use ListBlobsOptions() with setPrefix to filter based on prefix as shown below

ListBlobsOptions options=new ListBlobsOptions();
options.setPrefix("<<prefix>>");
Duration fromDays = Duration.of(10, ChronoUnit.MINUTES);
BlobContainerClient containerClient = blobServiceClient.getBlobContainerClient("containerName");
for (BlobItem blobItem : containerClient.listBlobs(options,fromDays)) {
            System.out.println("\t" + blobItem.getName());
}

Upvotes: 2

Fabio Maulo
Fabio Maulo

Reputation: 466

This is all you need

BlobContainer.ListBlobs(prefix, useFlatBlobListing: true, blobListingDetails: BlobListingDetails.None)
.OfType<CloudBlockBlob>()
.Where(x=> x.Name.EndsWith(".json"));

The prefix is just a partial path where search. The result is an IEnumerable<CloudBlockBlob>.

Upvotes: -1

Gaurav Mantri
Gaurav Mantri

Reputation: 136196

Is there a way to query/request container to return just blobs with specific extension?

Unfortunately no. You can't query blob storage to return blobs with a particular extension.

I don't want to loop through all the blobs in the container to do this.

If you're using Storage REST API, that's the only way to do it. You will need to list blobs in the container and then loop through the blobs and do the filtering based on extension (or any other criteria) on the client side.

Possible Solution

One possible solution would be to use Azure Search Service and have your blob metadata indexed there. Then you should be able to search for a particular extension and get the list of blobs.

Upvotes: 4

Related Questions