development

Amazon S3 버킷을 어떻게 검색합니까?

big-blog 2020. 6. 25. 07:32
반응형

Amazon S3 버킷을 어떻게 검색합니까?


수천 개의 파일이 들어있는 버킷이 있습니다. 버킷을 어떻게 검색합니까? 추천 할 수있는 도구가 있습니까?


S3는 네이티브가 실제 내용부터 "이 버킷 검색"이없는 것은 알 수 - 또한, S3가 제공 ALA보다 전통적인 데이터 스토어를 한 번에 액세스 여러 노드에 네이티브 방법이 없다는 기반 키 / 값이므로 (SELECT * FROM ... WHERE ...)(A SQL에가 모델).

당신이 할 필요가 수행하는 것은 ListBucket당신의 검색 인 - a를 양동이에 개체의 목록 다음으로 반복은 모든 항목에 걸쳐 당신이 구현하는 사용자 정의 작업을 수행을 얻을 수 있습니다.


여기에 추가하기위한 참고 사항 : 이제 3 년이 지난 지금 "S3 버킷을 검색하는 방법"을 입력하면이 게시물이 Google에서 1 위를 차지합니다.

아마도 당신은 더 복잡한 것을 찾고있을 것입니다. 그러나 여기에 착륙하여 제목으로 객체 (파일)를 찾는 방법을 알아 내려고한다면, 그것은 간단합니다.

버킷을 열고 오른쪽에서 "없음"을 선택한 다음 파일 이름을 입력하십시오.

http://docs.aws.amazon.com/AmazonS3/latest/UG/ListingObjectsinaBucket.html


다음은 AWS CLI를 사용하여 파일 이름을 검색하는 간단하고 못생긴 방법입니다 .

aws s3 ls s3://your-bucket --recursive | grep your-search | cut -c 32-

"버킷 검색"으로 설명 할 수있는 두 가지 다른 사용 사례가 있습니다.

  1. 버킷에 저장된 모든 객체 내부 에서 무언가를 검색합니다 . 이것은 해당 버킷의 모든 객체 (예 : 텍스트 파일) 등의 공통 형식을 가정합니다. 이와 같은 경우 Cody Caughlan이 방금 응답 한 것을 수행해야합니다. AWS S3 문서에는 AWS SDK for Java를 사용 하여이 작업을 수행하는 방법을 보여주는 예제 코드 가 있습니다. Java 용 AWS SDK를 사용하여 키 나열 (PHP 및 C # 예제도 있습니다).

  2. 목록 항목 해당 버킷에 포함 된 객체 에서 무언가를 검색합니다 . S3는 않습니다부분 구분 한 후 일치를 무너 접두사 정확히 일치 +를 허용하는 형태로,이에 대한 지원을. 자세한 내용은 AWS S3 개발자 안내서 에서 자세히 설명 합니다. 이를 통해 예를 들어 다음과 같은 객체 키로 사용하여 "폴더"를 구현할 수 있습니다.

    폴더 / 하위 폴더 /file.txt
    이 규칙을 준수하면 대부분의 S3 GUI (예 : AWS 콘솔)에 버킷의 폴더보기가 표시됩니다.


여러 가지 옵션이 있지만 간단한 "원샷"전체 텍스트 솔루션은 없습니다.

  1. 키 이름 패턴 검색 : 문자열로 시작하는 키 검색-키 이름을 신중하게 디자인하면 빠른 해결 방법이있을 수 있습니다.

  2. 키에 첨부 된 메타 데이터 검색 : 파일을 AWS S3에 게시 할 때 콘텐츠를 처리하고 일부 메타 정보를 추출하며이 메타 정보를 사용자 지정 헤더 형태로 키에 첨부 할 수 있습니다. 이를 통해 완전한 컨텐츠를 가져올 필요없이 키 이름과 헤더를 가져올 수 있습니다. 검색은 순차적으로 수행되어야하며 이에 대한 "sql like"검색 옵션이 없습니다. 파일이 크면 많은 네트워크 트래픽과 시간을 절약 할 수 있습니다.

  3. SimpleDB에 메타 데이터를 저장하십시오. 이전 포인트로 메타 데이터를 SimpleDB 에 저장합니다. 여기에는 SQL과 같은 select 문이 있습니다. 큰 데이터 세트의 경우 극복 할 수있는 SimpleDB 제한에 도달 할 수 있지만 (여러 SimpleDB 도메인의 파티션 메타 데이터) 실제로 멀어지면 다른 메타 데이터 유형의 데이터베이스를 사용해야합니다.

  4. 내용의 순차적 전체 텍스트 검색 -모든 키를 하나씩 처리합니다. 처리 할 키가 너무 많으면 매우 느립니다.

버전이 지정된 버킷을 사용하여 몇 년 동안 하루에 1440 버전의 파일 (분당 1 개)을 저장하는 것이 가능합니다. 그러나 순차적으로 버전을 이동해야하므로 이전 버전을 얻는 데 시간이 걸립니다. 때로는 레코드와 함께 간단한 CSV 인덱스를 사용하여 게시 시간과 버전 ID를 표시하여 이전 버전으로 빠르게 이동할 수 있습니다.

보시다시피, AWS S3는 전체 텍스트 검색을 위해 자체 설계되지 않았으며 간단한 스토리지 서비스입니다.


AWS는 SQL을 사용하여 S3 버킷을 쿼리하는 새로운 서비스를 출시했습니다. Amazon Athena https://aws.amazon.com/athena/


AWS에 있다고 가정하면 ... 그들의 CloudSearch 도구를 사용하고 싶다고 생각합니다. 검색하려는 데이터를 서비스에 넣으십시오. S3 키를 가리 킵니다.

http://aws.amazon.com/cloudsearch/


S3 콘솔에서 접두사로 검색

AWS 콘솔 버킷보기에서 직접

여기에 이미지 설명을 입력하십시오

s3-dist-cp를 사용하여 원하는 파일 복사

수천 또는 수백만 개의 파일이있는 경우 원하는 파일을 얻는 또 다른 방법은 분산 사본을 사용하여 다른 위치로 파일을 복사하는 것 입니다. Hadoop 작업의 EMR 에서 이를 실행합니다 . AWS의 멋진 점은 사용자 정의 S3 버전 s3-dist-cp 를 제공한다는 것 입니다. groupBy 필드에서 정규식을 사용하여 원하는 파일을 그룹화 할 수 있습니다. 예를 들어 EMR의 사용자 정의 단계에서이를 사용할 수 있습니다.

[
    {
        "ActionOnFailure": "CONTINUE",
        "Args": [
            "s3-dist-cp",
            "--s3Endpoint=s3.amazonaws.com",
            "--src=s3://mybucket/",
            "--dest=s3://mytarget-bucket/",
            "--groupBy=MY_PATTERN",
            "--targetSize=1000"
        ],
        "Jar": "command-runner.jar",
        "Name": "S3DistCp Step Aggregate Results",
        "Type": "CUSTOM_JAR"
    }
]

Windows를 사용하고 있고 좋은 grep대안을 찾을 시간이 없다면 빠르고 더러운 방법은 다음과 같습니다.

aws s3 ls s3://your-bucket/folder/ --recursive > myfile.txt

그런 다음 myfile.txt에서 빠른 검색을 수행하십시오.

"폴더"비트는 선택 사항입니다.

AWS CLI를 설치하지 않은 경우 PS-Chocolatey 패키지 관리자를 사용하는 하나의 라이너

choco install awscli

P.P.S. If you don't have the Chocolatey package manager - get it! Your life on Windows will get 10x better. (I'm not affiliated with Chocolatey in any way, but hey, it's a must-have, really).


This is little bit old thread - but maybe help someone who still search - I'm the one who search for that a year.

Solution may be "AWS Athena" where you can search over data like this

'SELECT user_name FROM S3Object WHERE cast(age as int) > 20'

https://aws.amazon.com/blogs/developer/introducing-support-for-amazon-s3-select-in-the-aws-sdk-for-javascript/

Currently pricing is $5 for 1TB data - so for example, if your query search over one 1TB file 3times your cost is $15 - but for example if there is only 1column in "converted columnar format" what you want read, you'll pay 1/3 of price means $1.67/TB.


Another option is to mirror the S3 bucket on your web server and traverse locally. The trick is that the local files are empty and only used as a skeleton. Alternatively, the local files could hold useful meta data that you normally would need to get from S3 (e.g. filesize, mimetype, author, timestamp, uuid). When you provide a URL to download the file, search locally and but provide a link to the S3 address.

Local file traversing is easy and this approach for S3 management is language agnostic. Local file traversing also avoids maintaining and querying a database of files or delays making a series of remote API calls to authenticate and get the bucket contents.

You could allow users to upload files directly to your server via FTP or HTTP and then transfer a batch of new and updated files to Amazon at off peak times by just recursing over the directories for files with any size. On the completion of a file transfer to Amazon, replace the web server file with an empty one of the same name. If a local file has any filesize then serve it directly because its awaiting batch transfer.


Try this command:

aws s3api list-objects --bucket your-bucket --prefix sub-dir-path --output text --query 'Contents[].{Key: Key}'

Then you can pipe this into a grep to get specific file types to do whatever you want with them.


Take a look at this documentation: http://docs.aws.amazon.com/AWSSDKforPHP/latest/index.html#m=amazons3/get_object_list

You can use a Perl-Compatible Regular Expression (PCRE) to filter the names.


The way I did it is: I have thousands of files in s3. I saw the properties panel of one file in the list. You can see the URI of that file and I copy pasted that to the browser - it was a text file and it rendered nicely. Now I replaced the uuid in the url with the uuid that I had at hand and boom there the file is.

I wish AWS had a better way to search a file, but this worked for me.


I did something as below to find patterns in my bucket

def getListOfPrefixesFromS3(dataPath: String, prefix: String, delimiter: String, batchSize: Integer): List[String] = {
    var s3Client = new AmazonS3Client()
    var listObjectsRequest = new ListObjectsRequest().withBucketName(dataPath).withMaxKeys(batchSize).withPrefix(prefix).withDelimiter(delimiter)
    var objectListing: ObjectListing = null
    var res: List[String] = List()

    do {
      objectListing = s3Client.listObjects(listObjectsRequest)
      res = res ++ objectListing.getCommonPrefixes
      listObjectsRequest.setMarker(objectListing.getNextMarker)
    } while (objectListing.isTruncated)
    res
  }

For larger buckets this consumes too much of time since all the object summaries are returned by the Aws and not only the ones that match the prefix and the delimiter. I am looking for ways to improve the performance and so far i've only found that i should name the keys and organise them in buckets properly.


Status 2018-07: Amazon do have native sql like search for csv and json files!

https://aws.amazon.com/blogs/developer/introducing-support-for-amazon-s3-select-in-the-aws-sdk-for-javascript/


나는 다음과 같은 방법으로 시도했다

aws s3 ls s3://Bucket1/folder1/2019/ --recursive |grep filename.csv

파일이 존재하는 실제 경로를 출력합니다

2019-04-05 01:18:35     111111 folder1/2019/03/20/filename.csv

참고 URL : https://stackoverflow.com/questions/4979218/how-do-you-search-an-amazon-s3-bucket

반응형