Export nach Apache Arrow
Alle Ergebnisse einer Abfrage können mit der Funktion to_arrow_table in eine Apache Arrow Table exportiert werden. Alternativ können Ergebnisse mit der Funktion to_arrow_reader als RecordBatchReader zurückgegeben und Batch für Batch gelesen werden. Außerdem können Relationen, die mit DuckDBs Relationaler API aufgebaut wurden, ebenfalls exportiert werden.
Deprecated Die Funktionen
fetch_arrow_table,fetch_record_batchundfetch_arrow_readersind veraltet. Verwenden Sie stattdessento_arrow_tableundto_arrow_reader.
Export in eine Arrow Table
import duckdbimport 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 Tableresults = duckdb.sql("SELECT * FROM my_arrow_table").to_arrow_table()Export als RecordBatchReader
import duckdbimport 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 RecordBatchReaderchunk_size = 1_000_000result = 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 emptywhile (batch := result.read_next_batch()): # Process a single chunk here print(batch.to_pandas())Export aus der Relationalen API
Arrow-Objekte können auch aus der Relationalen API exportiert werden. Eine Relation lässt sich mit DuckDBPyRelation.to_arrow_table in eine Arrow Table und mit DuckDBPyRelation.to_arrow_reader in einen Arrow-Record-Batch-Reader umwandeln.
import duckdb
# connect to an in-memory databasecon = 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 Arrowrel = con.table("integers")relation_as_arrow = rel.to_arrow_table()
# Calculate a result using that relation and export that result to Arrowres = rel.aggregate("sum(i)").execute()arrow_table = res.to_arrow_table()
# You can also create an Arrow record batch reader from a relationarrow_batch_reader = res.to_arrow_reader()while (batch := arrow_batch_reader.read_next_batch()): # Process a single chunk here print(batch.to_pandas())