读取和写入 Apache ORC 格式#

Apache ORC 项目为数据分析系统提供了一种标准化的开源列式存储格式。它最初是为 Apache Hadoop 与诸如 Apache DrillApache HiveApache ImpalaApache Spark 等系统一起使用而创建的,这些系统都将其作为高性能数据 IO 的共享标准。

Apache Arrow 是使用 ORC 文件读取或写入数据时理想的内存表示层。

获取支持 ORC 的 pyarrow#

如果您使用 pip 或 conda 安装了 pyarrow,它应该会内置 ORC 支持进行构建

>>> from pyarrow import orc

如果您从源代码构建 pyarrow,则在编译 C++ 库时必须使用 -DARROW_ORC=ON,并在构建 pyarrow 时启用 ORC 扩展。有关更多详细信息,请参见Python 开发页面。

读取和写入单个文件#

函数 read_table()write_table() 分别读取和写入 pyarrow.Table 对象。

让我们看一个简单的表

>>> import numpy as np
>>> import pyarrow as pa

>>> table = pa.table(
...     {
...         'one': [-1, np.nan, 2.5],
...         'two': ['foo', 'bar', 'baz'],
...         'three': [True, False, True]
...     }
... )

我们使用 write_table 将其写入 ORC 格式

>>> from pyarrow import orc
>>> orc.write_table(table, 'example.orc')

这将创建一个单独的 ORC 文件。在实践中,一个 ORC 数据集可能由许多目录中的许多文件组成。我们可以使用 read_table 读回单个文件

>>> table2 = orc.read_table('example.orc')

您可以传递要读取的列的子集,这比读取整个文件要快得多(由于列式布局)

>>> orc.read_table('example.orc', columns=['one', 'three'])
pyarrow.Table
one: double
three: bool
----
one: [[-1,nan,2.5]]
three: [[true,false,true]]

我们不需要使用字符串来指定文件的来源。它可以是以下任何一种

  • 文件路径,为字符串

  • Python 文件对象

  • pathlib.Path 对象

  • 来自 PyArrow 的 NativeFile

一般来说,Python 文件对象的读取性能最差,而字符串文件路径或 NativeFile 的实例(尤其是内存映射)的性能将是最好的。

我们还可以通过 pyarrow.dataset 接口读取包含多个 ORC 文件的分区数据集。

另请参阅

数据集文档.

ORC 文件写入选项#

write_table() 具有许多选项,用于控制写入 ORC 文件时的各种设置。

  • file_version,要使用的 ORC 格式版本。'0.11' 确保与较旧的读取器的兼容性,而 '0.12' 是较新的版本。

  • stripe_size,用于控制列条纹中数据的近似大小。当前默认为 64MB。

有关更多详细信息,请参见 write_table() 的文档字符串。

更细粒度的读取和写入#

read_table 使用 ORCFile 类,该类具有其他功能

>>> orc_file = orc.ORCFile('example.orc')
>>> orc_file.metadata

-- metadata --
>>> orc_file.schema
one: double
two: string
three: bool
>>> orc_file.nrows
3

有关更多详细信息,请参见 ORCFile 的文档字符串。

正如您在 Apache ORC 格式中了解到的那样,一个 ORC 文件由多个条纹组成。read_table 将读取所有条纹并将它们连接成一个表。您可以使用 read_stripe 读取各个条纹

>>> orc_file.nstripes
1
>>> orc_file.read_stripe(0)
pyarrow.RecordBatch
one: double
two: string
three: bool

我们可以使用 ORCWriter 写入 ORC 文件

>>> with orc.ORCWriter('example2.orc') as writer:
...     writer.write(table)

压缩#

在编码过程(字典、RLE 编码)之后,可以压缩行组中列内的数据页。在 PyArrow 中,默认情况下我们不使用压缩,但也支持 Snappy、ZSTD、Gzip/Zlib 和 LZ4

>>> orc.write_table(table, where, compression='uncompressed')
>>> orc.write_table(table, where, compression='gzip')
>>> orc.write_table(table, where, compression='zstd')
>>> orc.write_table(table, where, compression='snappy')

Snappy 通常会带来更好的性能,而 Gzip 可能会产生较小的文件。

从云存储读取#

除了本地文件外,pyarrow 还通过 filesystem 关键字支持其他文件系统,例如云文件系统

>>> from pyarrow import fs

>>> s3  = fs.S3FileSystem(region="us-east-2")
>>> table = orc.read_table("bucket/object/key/prefix", filesystem=s3)

另请参阅

文件系统文档.