首页 > 解决方案 > 如何通过键索引存储在 S3 中的 JSON 文件?

问题描述

假设我想在 S3 中存储数百个 JSON 文件。所有这些 JSON 文件都具有相同的架构。我想通过键和值来搜索这些 JSON 文件:例如,查找键值a= "abc*" 和键值x= "xyz" 的所有 JSON 文件。我希望搜索返回与查询匹配的文件名和键。

通过键索引存储在 S3 中的 JSON 文件的最佳方法是什么?

这是我之前的问题的后续

标签: jsonamazon-s3searchindexing

解决方案


您可能要考虑使用S3 Select.

借助 Amazon S3 Select,您可以使用简单的结构化查询语言 (SQL) 语句来过滤 Amazon S3 对象的内容并仅检索您需要的数据子集。通过使用 Amazon S3 Select 筛选此数据,您可以减少 Amazon S3 传输的数据量,从而降低检索此数据的成本和延迟。

Amazon S3 Select 适用于以 CSV、JSON 或 Apache Parquet 格式存储的对象。

S3 Select 上的完整文档

这是一篇关于如何使用S3 Select.

https://aws.amazon.com/blogs/storage/querying-data-without-servers-or-databases-using-amazon-s3-select/

示例代码如下所示:

import boto3

# S3 bucket to query (Change this to your bucket)
S3_BUCKET = 'greg-college-data'

s3 = boto3.client('s3')

r = s3.select_object_content(
        Bucket=S3_BUCKET,
        Key='COLLEGE_DATA_2015.csv',
        ExpressionType='SQL',
        Expression="select \"INSTNM\" from s3object s where s.\"STABBR\" in ['OR', 'IA']",
        InputSerialization={'CSV': {"FileHeaderInfo": "Use"}},
        OutputSerialization={'CSV': {}},
)

for event in r['Payload']:
    if 'Records' in event:
        records = event['Records']['Payload'].decode('utf-8')
        print(records)

代码来源


推荐阅读