Sub topic 2
Writing a Partitioned Dataset with PyArrow
This chapter assumes basic Python, table and column concepts, and familiarity with Parquet files. You will use pyarrow.dataset to write a logical table across directories and read only the data needed for a query.
Writing a partitioned dataset with `write_dataset`
A partitioned dataset stores rows in separate directories based on column values. Hive-style partitioning names each directory with column=value, such as year=2024/country=DE.
import pyarrow as pa
import pyarrow.dataset as ds
table = pa.table({
"year": [2023, 2023, 2024, 2024],
"country": ["DE", "FR", "DE", "FR"],
"amount": [10.5, 20.0, 7.25, 3.0],
})
partitioning = ds.partitioning(
pa.schema([
("year", pa.int64()),
("country", pa.string()),
]),
flavor="hive",
)
ds.write_dataset(
table,
"sales",
format="parquet",
partitioning=partitioning,
existing_data_behavior="overwrite_or_ignore",
)This creates paths similar to sales/year=2024/country=DE/part-0.parquet. The partition columns remain part of the logical table, even though their values are represented by directory names.
Opening and inspecting the dataset
Pass partitioning="hive" when opening the directory. PyArrow discovers Parquet files and creates a dataset made of file-level fragments.
dataset = ds.dataset("sales", format="parquet", partitioning="hive")
print(dataset.schema)
print(sorted(dataset.files))
for fragment in dataset.get_fragments():
print(fragment.path, fragment.partition_expression)A fragment's partition expression records the values encoded by its path.
Building filters and pruning partitions
Build filters with ds.field. Combine expressions with & and |; parenthesize each comparison.
flt = (ds.field("year") == 2024) & (ds.field("country") == "DE")
result = dataset.to_table(
filter=flt,
columns=["year", "country", "amount"],
)
print(result.to_pydict())Because both fields are partition columns, PyArrow can prune the directory tree before opening unrelated Parquet files. This is different from filtering after loading all rows. Selecting columns also enables column projection, so PyArrow reads only the requested columns from matching files.
Exercise
Why might filtering on amount read more data than filtering on year?
Show answer
year is encoded in directory names, so PyArrow can skip whole partitions. amount is stored inside Parquet files, so PyArrow may need to inspect file metadata or row groups before excluding rows.