Ian Warburton
Ian Warburton

Reputation: 15666

Check if a key with a certain prefix exists in Amazon S3 bucket

How would I check if there's a key that starts with a particular prefix, similar to "folders"?

Upvotes: 12

Views: 11468

Answers (3)

upog
upog

Reputation: 5521

Required: aws-java-sdk jar

credentials = new BasicAWSCredentials(accessKey, secretKey);
config = new ClientConfiguration();
client = new AmazonS3Client(credentials, config );
client.doesBucketExist(bucketName+"/prefix");

Upvotes: 1

Troy
Troy

Reputation: 5399

To iterate over all S3 files in your bucket that start with 'some/prefix/' in ruby, do the following using the aws-sdk gem:

AWS.config :access_key_id => "foo", :secret_access_key => "bar"
s3 = AWS::S3.new
s3.buckets['com.mydomain.mybucket'].objects.with_prefix('some/prefix/').each do |object|
    # Do something with object (an S3 object)
end

Upvotes: 2

vsekhar
vsekhar

Reputation: 5520

The docs say it is possible to specify a prefix parameter when asking for a list of keys in a bucket. You can set the max-keys parameter to 1 for speed. If the list is non-empty, you know the prefix exists.

Tools like boto's bucket.list() function expose prefixing and paging as well.

Upvotes: 6

Related Questions