I want to get the number of folders in S3

Asked 1 months ago, Updated 1 months ago, 4 views

Is it possible to retrieve the number of folders in S3?

For example,

jazz/chill/chord_01/xxx.wav
jazz/chill/chord_01/xxx.wav
jazz/chill/chord_01/xxx.wav
jazz/chill/chord_02/xxx.wav
jazz/chill/chord_03/xxx.wav

when configuring
[jazz/chill/chord_01/, jazz/chill/chord_02, jazz/chill/chord_03/].count 
=>3

`

I would like to retrieve the number of folders as shown in .

I was able to get the file count information with the following code:
I don't know how to get folder information only.

def get_files(file_path='')
  [email protected]_objects({
    bucket —Settings.aws.bucket_name,
    prefix —file_path
  })
  resp.to_h[:contents]
end

I would appreciate your help.

ruby-on-rails ruby aws amazon-s3

2022-09-30 14:10

2 Answers

Ruby's own code doesn't come out at all, so please let me know your policy.

https://docs.aws.amazon.com/ja_jp/AmazonS3/latest/dev/ListingKeysHierarchy.html

If you look at the pages above, you can see that api in awss3 can retrieve the next layer of data from prefix by listing object with delimiter and prefix.

I think it would be better to use aws-sdk-s3 to list_objects under the following conditions.(Not verified)

@s3.list_objects({
    bucket —Settings.aws.bucket_name,
    prefix: 'jazz/chill/',
    delimiter: '/'
  })


2022-09-30 14:10

S3 does not have the concept of a folder, so you can count the unique names by considering the key you get as a file name and taking out the parts you want to treat as folders, such as dirname.


2022-09-30 14:10

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.