gpt4 book ai didi

java - 如何使用AWS Java SDK通过s3api查询来获取对象列表?

转载 作者:行者123 更新时间:2023-11-30 05:26:01 26 4
gpt4 key购买 nike

我正在使用 AWS java SDK 进行开发。我想获得一个带有过滤器的对象列表,例如按上次修改日期过滤器。我可以在 s3api 上看到这个功能,如下

aws s3api list-objects 
--bucket "myS3-BucketName"
--query "Contents[?LastModified>=`2018-02-01`].{Key: Key, Size: Size, LastModified: LastModified}"
--max-items 10"

我在Java SDK中找不到类似的解决方案。我如何使用 Java SDK 来完成这项工作?

最佳答案

使用v2在 AWS SDK for Java 中,我创建了以下实用程序方法:

/**
* Gets S3 objects that reside in a specific bucket and whose keys conform to the
* specified prefix using v2 of the AWS Java SDK.
* <br><br>
* The objects returned will have a last-modified date between {@code start} and
* {@code end}.
* <br><br>
* Any objects that have been modified outside of the specified date-time range will
* not be returned.
*
* @param s3Client The v2 AWS S3 client used to make the request to S3.
* @param bucket The bucket where the S3 objects are located.
* @param prefix The common prefix that the keys of the S3 objects must conform to.
* @param start The objects returned will have been modified after this instant.
* @param end The objects returned will have been modified before this instant.
* @return A {@link Stream} of {@link S3Object} objects.
*/
public static Stream<S3Object> getObjects(S3Client s3Client, String bucket,
String prefix, Instant start,
Instant end) {
return s3Client.listObjectsV2Paginator(builder -> builder.bucket(bucket)
.prefix(prefix).build())
.stream()
.map(ListObjectsV2Response::contents)
.flatMap(List::stream)
.filter(s3Object -> {
Instant lastModified = s3Object.lastModified();
return !start.isAfter(lastModified) && !end.isBefore(lastModified);
});
}

以下代码在逻辑上与您的示例等效:

S3Client s3Client = S3Client.create();
String bucket = "myS3-BucketName";
Instant before = Instant.parse("2018-02-01T00:00:00Z");
Instant after = Instant.MAX;

Stream<S3Object> firstTenObjects =
getObjects(s3Client, bucket, "", before, after).limit(10);

您可以使用以下方法从 Stream 中的每个 S3Object 获取您要查找的数据:

关于java - 如何使用AWS Java SDK通过s3api查询来获取对象列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58585528/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com