1

Is it possible to find/delete S3 object if we only have part of the object key?

Scenario : Let say user store 123123.jpeg in S3 (bucket name : mybucket) and I need to delete this object but I only know 123123, not the whole key with the extension .jpeg.

I'm aware that we can find object in a bucket based on prefix but AFAIK this only apply if the object exist in path inside the bucket, eg : mybucket/imgpath/123123.jpeg

shkhssn
  • 303
  • 1
  • 4
  • 17
  • Check this question: http://stackoverflow.com/questions/8027265/how-to-list-all-aws-s3-objects-in-a-bucket-using-java – Abhay Jain Nov 03 '16 at 08:36

1 Answers1

1

You can use brute force:

List<String> matchingKeys = new ArrayList<>();
Predicate<String> predicate = Pattern.compile(".*/" + filename + "\\.\\w+").asPredicate();
for (ObjectListing listing = s3.listObjects(bucketName, "/");; listing = s3.listNextBatchOfObjects(listing)) {
    listing.getObjectSummaries().stream()
      .map(S3ObjectSummary::getKey)
      .filter(predicate)
      .forEach(matchingKeys::add);
    if (!listing.isTruncated()) {
        break;
    }
}

Instead of collecting the hits, you could just delete:

.forEach(key -> s3.deleteObject(bucketName, key));

Note: This uses a regex suitable for your scenario of finding a key given the extension-less filename, but you could adjust the regex as you need. For example, to find all keys that have a substring anywhere in their key, use the regex

".*" + substring ".*"

Or case insensitive

"(?i).*" + substring ".*"

etc.

Disclaimer: Code may not compile or work as it was thumbed in on my phone (but there's a reasonable chance it will work)

Bohemian
  • 412,405
  • 93
  • 575
  • 722