繁体   English   中英

使用 Pyarrow 从 S3 parquet 文件中获取元数据

[英]Get Metadata from S3 parquet file using Pyarrow

我在 s3 中有一个镶木地板文件,我将每周自动向该文件附加额外的数据。 数据有 5 分钟间隔的时间戳。 我不想在我的更新过程中 append 任何重复的数据,所以我想要完成的是只读取保存在 s3 中的数据中的最大/最旧时间戳。 然后,我将确保我将附加的数据中的所有时间戳都比附加之前的时间更早。 随着数据集的不断增长,我不想从 s3 读取整个数据集以提高速度/保留 memory。

这是我现在读取整个文件的示例:

from pyarrow import fs 
import pyarrow.parquet as pq

s3, path = fs.S3FileSystem(access_key, secret_key).from_uri(uri)
dataset = pq.ParquetDataset(path, filesystem=s3)
table = dataset.read()

但我正在寻找更像这样的东西(我知道这是不正确的,但希望它传达了我想要完成的目标):

max_date = pq.ParquetFile(path, filesystem=s3).metadata.row_group(0).column('timestamp').statistics['max']

我对使用 Pyarrow 和 AWS 都很陌生,所以任何帮助都会很棒(包括我描述的问题的替代解决方案)。

从纯粹迂腐的角度来看,我会将问题陈述表述为“我在 S3 中有一个镶木地板数据集,并将定期附加新的镶木地板文件”。 我只提到,因为 pyarrow 文档是在考虑该术语的情况下编写的(例如,您不能 append 使用 pyarrow 到镶木地板文件,但您可以 append 到镶木地板数据集),因此它可能有助于理解。

pyarrow 数据集 API 目前没有任何操作来检索数据集统计信息(将功能请求为 JIRA 可能不是一个坏主意)。 但是,它可以帮助您找到碎片。 你所拥有的对我来说似乎并不遥远。

s3, path = fs.S3FileSystem(access_key, secret_key).from_uri(uri)
# At this point a call will be made to S3 to list all the files
# in the directory 'path'
dataset = pq.ParquetDataset(path, filesystem=s3)
max_timestamp = None
for fragment in dataset.get_fragments():
  field_index = fragment.physical_schema.get_field_index('timestamp')
  # This will issue a call to S3 to load the metadata
  metadata = fragment.metadata
  for row_group_index in range(metadata.num_row_groups):
    stats = metadata.row_group(row_group_index).column(field_index).statistics
    # Parquet files can be created without statistics
    if stats:
      row_group_max = stats.max
      if max_timestamp is None or row_group_max > max_timestamp:
        max_timestamp = row_group_max
print(f"The maximum timestamp was {max_timestamp}")

我已经注释了实际调用 S3 的位置。 这肯定会比加载所有数据更快,但仍然会有一些开销,随着您添加更多文件而增加。 如果您在 AWS 区域之外运行,此开销可能会非常高。 您可以通过并行扫描片段来缓解这种情况,但这将是额外的工作。

每当您更新数据集中的数据时,将 max_timestamp 存储在专用统计文件中会更快。 这样,您只需要阅读一个小文件。 如果您自己管理写入,您可能会查看像Apache Iceberg这样的表格格式,这是一种标准格式,用于存储有关数据集的此类额外信息和统计信息(Arrow 称之为“数据集”,Iceberg 称之为“表格”) .

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM