⌘+k ctrl+k
1.4 (LTS)
搜索快捷键 cmd + k | ctrl + k
导出至 Apache Arrow

查询的所有结果都可以使用 fetch_arrow_table 函数导出为 Apache Arrow 表。或者,也可以使用 arrow 函数将结果作为 RecordBatchReader 返回,并以每次一批的方式读取结果。此外,使用 DuckDB 的 关系 API (Relational API) 构建的关系也可以进行导出。

导出为 Arrow 表

import duckdb
import pyarrow as pa

my_arrow_table = pa.Table.from_pydict({'i': [1, 2, 3, 4],
                                       'j': ["one", "two", "three", "four"]})

# query the Apache Arrow Table "my_arrow_table" and return as an Arrow Table
results = duckdb.sql("SELECT * FROM my_arrow_table").fetch_arrow_table()

导出为 RecordBatchReader

import duckdb
import pyarrow as pa

my_arrow_table = pa.Table.from_pydict({'i': [1, 2, 3, 4],
                                       'j': ["one", "two", "three", "four"]})

# query the Apache Arrow Table "my_arrow_table" and return as an Arrow RecordBatchReader
chunk_size = 1_000_000
result = duckdb.sql("SELECT * FROM my_arrow_table").arrow(chunk_size)

# Loop through the results. A StopIteration exception is thrown when the RecordBatchReader is empty
while (batch := result.read_next_batch()):
    # Process a single chunk here
    print(batch.to_pandas())

从关系 API 导出

Arrow 对象也可以从关系 API 中导出。可以使用 DuckDBPyRelation.fetch_arrow_tableDuckDBPyRelation.to_arrow_table 函数将关系转换为 Arrow 表;也可以使用 DuckDBPyRelation.arrowDuckDBPyRelation.fetch_arrow_reader 函数将其转换为 Arrow 记录批处理读取器 (Record Batch Reader)。

import duckdb

# connect to an in-memory database
con = duckdb.connect()

con.execute('CREATE TABLE integers (i integer)')
con.execute('INSERT INTO integers VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9), (NULL)')

# Create a relation from the table and export the entire relation as Arrow
rel = con.table("integers")
relation_as_arrow = rel.to_arrow_table() # or .fetch_arrow_table()

# Calculate a result using that relation and export that result to Arrow
res = rel.aggregate("sum(i)").execute()
arrow_table = res.to_arrow_table() # or .fetch_arrow_table()

# You can also create an Arrow record batch reader from a relation
arrow_batch_reader = res.arrow() # or .fetch_arrow_reader()
while (batch := arrow_batch_reader.read_next_batch()):
    # Process a single chunk here
    print(batch.to_pandas())
© 2025 DuckDB 基金会,阿姆斯特丹,荷兰
行为准则 商标使用指南