首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用获取以查询为s3api的对象列表?

如何使用获取以查询为s3api的对象列表?
EN

Stack Overflow用户
提问于 2019-10-28 03:38:35
回答 1查看 2.4K关注 0票数 4

我正在使用AWS进行开发。我想通过上次修改的日期得到一个带有过滤器的对象列表。我可以在s3api上看到如下所示的特性

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-28 03:56:30

使用AWS的v2,我创建了以下实用方法:

代码语言:javascript
复制
/**
 * 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);
            });
}

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

代码语言:javascript
复制
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);

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58585528

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档