Apache Arrow로 내보내기

Apache Arrow로 내보내기 (Export to Apache Arrow)

쿼리 결과 전체를 to_arrow_table 함수로 Apache Arrow Table로 내보낼 수 있어요. 또는 to_arrow_reader 함수로 결과를 RecordBatchReader로 받아 배치(batch) 단위로 하나씩 읽을 수도 있어요. 여기에 더해 DuckDB의 Relational API로 만든 relation도 내보낼 수 있어요.

출처: 공식문서

참고fetch_arrow_table, fetch_record_batch, fetch_arrow_reader 함수는 더 이상 쓰지 않아요(deprecated). 앞으로는 to_arrow_tableto_arrow_reader를 쓰세요.

Arrow Table로 내보내기

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").to_arrow_table()

RecordBatchReader로 내보내기

결과를 배치 단위로 스트리밍하며 읽고 싶다면 to_arrow_reader를 써요. read_next_batch()가 레코드 배치를 하나씩 돌려주고, 배치가 비면 StopIteration 예외가 던져져요.

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").to_arrow_reader(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())

Relational API에서 내보내기

Arrow 객체는 Relational API에서도 내보낼 수 있어요. relation을 Arrow 테이블로 바꾸려면 DuckDBPyRelation.to_arrow_table, Arrow 레코드 배치 리더로 바꾸려면 DuckDBPyRelation.to_arrow_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()

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

# You can also create an Arrow record batch reader from a relation
arrow_batch_reader = res.to_arrow_reader()
while (batch := arrow_batch_reader.read_next_batch()):
    # Process a single chunk here
    print(batch.to_pandas())

더 알아보기 (Learn more)