Leem.fin
Leem.fin

Reputation: 42582

AWS Ruby SDK , check a key exists always gives 'false'

In AWS S3, I have a bucket named my-bucket, I am using AWS Ruby SDK to access my bucket.

under my-bucket I have the following directory structure in S3 (I know it is not called "directory" in S3, but just to show the idea):

my-bucket/
    customers/
         products/
              - data1.txt
              - data2.txt
              ...

I want to check does my-bucket/customers/products exist with AWS Ruby SDK, I tried the following code:

s3 = Aws::S3::Resource.new
bucket = s3.bucket("my-bucket")
result = bucket.object("customers/products").exists?

But the result gives false, even though I do have that directory in S3, where am I wrong?

Upvotes: 0

Views: 1070

Answers (3)

davideghz
davideghz

Reputation: 3685

In Ruby sdk V2 the method with_prefix is not defined:

given an object with key like: dir1/dir2/object.jpg

try something like the following

bucket.objects(prefix: 'dir1/dir2').any?

or directly check for object existence

bucket.object('dir1/dir2/object.jpg').exists?

Upvotes: 0

Mark B
Mark B

Reputation: 200446

That's because "customers/products" doesn't exist as an object. It is just a prefix for some objects that do exist. You stated:

I know it is not called "directory" in S3

However it's more than just a different term for directories in S3. Directories (or folders) don't exist in S3 at all. There are just objects with keys. It's like a single flat directory, where your filenames can have slash characters in them.

Most S3 browsing applications will interpret slashes in key names as "directories" and display objects in a hierarchical fashion like a filesystem for convenience sake, but those directories/folders don't actually exist in S3.

As pointed out in the other answer, your best bet is to check if any objects exist that contain that prefix.

Upvotes: 5

Anurag Verma
Anurag Verma

Reputation: 495

Use bucket.objects.with_prefix("customers/products").any?

Upvotes: 0

Related Questions