Sub topic 10
Partition pruning: skipping files you do not need
This chapter assumes you can write and open a Hive-partitioned Parquet dataset with pyarrow.dataset, and that you know what a filter expression built with ds.field looks like. You should also know that a dataset is made of fragments, and that each fragment is usually one file.
What pruning means
Partition pruning is the step where the scanner decides, before it opens any file, that a fragment cannot contain matching rows. It then skips that fragment completely. No bytes are read, and no Parquet footer is parsed.
The decision relies on the partition expression attached to each fragment. When discovery finds sales/year=2024/country=DE/part-0.parquet, it records the expression (year == 2024) and (country == "DE") for that fragment. When you pass a filter, PyArrow simplifies it against each fragment's partition expression. If the result is always false, the fragment is dropped.
Pruning is one of three levels at which a filter can save work.
| Level | What is skipped | Information used | Cost to decide |
|---|---|---|---|
| Partition pruning | Whole files | Directory names | None, the names are already known |
| Row group pruning | Row groups inside a file | Min/max statistics in the Parquet footer | One footer read per file |
| Row filtering | Individual rows | The actual values | The data must be decoded |
Only the first level is free. The other two require opening files.
A runnable example
The following script builds a small dataset and then asks the dataset which fragments survive a filter. get_fragments accepts a filter argument and applies only the partition-level simplification, so it shows pruning in isolation.
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],
})
part = ds.partitioning(
pa.schema([("year", pa.int64()), ("country", pa.string())]),
flavor="hive",
)
ds.write_dataset(
table,
"sales",
format="parquet",
partitioning=part,
existing_data_behavior="overwrite_or_ignore",
)
dataset = ds.dataset("sales", format="parquet", partitioning="hive")
flt = (ds.field("year") == 2024) & (ds.field("country") == "DE")
print("All fragments:")
for fragment in dataset.get_fragments():
print(" ", fragment.path)
print("Surviving fragments:")
for fragment in dataset.get_fragments(filter=flt):
print(" ", fragment.path, "|", fragment.partition_expression)
print(dataset.to_table(filter=flt).to_pydict())Four fragments exist, and only sales/year=2024/country=DE/part-0.parquet survives. The other three files are never opened by the final to_table call either.
What pruning can and cannot do
Pruning works on the partition expression, so it only helps when the filter mentions partition columns in a form the simplifier understands.
These filters prune well:
- Equality:
ds.field("year") == 2024 - Ranges:
ds.field("year") >= 2023 - Membership:
ds.field("country").isin(["DE", "FR"]) - Conjunctions of the above joined with
&
Disjunctions with | also work when each branch refers to partition columns. A fragment is dropped only when every branch is false for it.
These filters do not prune, or prune only partially:
- A filter on a non-partition column such as
amount > 10. Fragments cannot be ruled out from their names, so all of them stay in the scan. Parquet statistics may still skip row groups. - A filter that wraps the partition column in a computation the simplifier cannot reason about. Compare the raw column to a constant whenever you can.
- A filter whose literal has a different type than the partition field. Casting the field or the literal to match is safer than relying on implicit conversion.
A mixed filter is split by the scanner. The partition part prunes fragments, and the remainder is applied to the rows that are read.
import pyarrow.dataset as ds
dataset = ds.dataset("sales", format="parquet", partitioning="hive")
mixed = (ds.field("year") == 2024) & (ds.field("amount") > 5)
survivors = [f.path for f in dataset.get_fragments(filter=mixed)]
print(survivors)
print(dataset.to_table(filter=mixed).to_pydict())Here year == 2024 removes the 2023 files. amount > 5 cannot remove any more files by name, so both 2024 fragments are listed. The row filter then drops the row with amount equal to 3.0.
Types matter: the partition schema controls comparisons
If you open the dataset with partitioning="hive" and no schema, PyArrow infers the type of each partition field from the directory text. A value like 2024 becomes an integer. A value such as 2024-01 stays a string. Inference looks at what it finds, so a column that is numeric in one directory and not in another can behave unexpectedly.
Declare the schema when the type matters, especially for dates and for numeric codes with leading zeros.
import pyarrow as pa
import pyarrow.dataset as ds
part = ds.partitioning(
pa.schema([("year", pa.int16()), ("country", pa.string())]),
flavor="hive",
)
dataset = ds.dataset("sales", format="parquet", partitioning=part)
print(dataset.schema)
flt = ds.field("year") == 2024
print([f.path for f in dataset.get_fragments(filter=flt)])With an explicit int16, the comparison year == 2024 is evaluated against an int16 field. Comparing a string partition field to an integer literal, or the reverse, is a common reason a filter returns no rows or raises a type error.
Verifying that pruning happened
Do not assume that a filter pruned. Check it. There are three practical ways.
- Count fragments with and without the filter, as in the examples above.
- Compare timing for a filtered and an unfiltered scan on realistic data.
- Inspect which paths the scanner would read, using
get_fragments(filter=...)before you callto_table.
import pyarrow.dataset as ds
dataset = ds.dataset("sales", format="parquet", partitioning="hive")
flt = ds.field("country") == "FR"
total = len(list(dataset.get_fragments()))
kept = len(list(dataset.get_fragments(filter=flt)))
print(f"kept {kept} of {total} fragments")A ratio close to 1 for a filter you expected to be selective means the filter is not touching the partition columns, or the layout does not match how you query.
Edge cases and failure modes
- Missing partition column in a filter. Filtering on a name that is not in the dataset schema raises an error at scan time. Partition columns appear in the schema only if discovery or your declared partitioning supplied them.
- Directory partitioning without a schema. Paths hold only values, so the reader cannot name or type the field. Pass a schema, or the values will not be exposed as columns and cannot be filtered.
- Null partition values. A null in a partition column is written to a placeholder directory such as
__HIVE_DEFAULT_PARTITION__in Hive flavor. Whether a null filter prunes depends on how that placeholder is read back, so test it on your own data before relying on it. - Files outside the layout. A stray file that does not follow the
key=valuepattern gets no partition expression. It can never be pruned and is read for every query. - Partition column also stored in the file. If a Parquet file physically holds a column with the same name as a partition field, the two can conflict. Keep partition columns out of the file body, which
write_datasetdoes for you. - Over-partitioning. Pruning is cheap, but listing and opening thousands of tiny files is not. Fine partitions make each surviving fragment cheap to skip and expensive to read in bulk.
Choosing a layout with pruning in mind
Put the columns you filter on most often into the partition schema, and keep their cardinality low enough that each directory still holds reasonably large files. A date split by year and month prunes well for time-range queries. A partition by user ID produces one tiny file per user and defeats the purpose.
Order the partition columns from the one you filter on most to the one you filter on least. The order only changes the directory nesting, and it does not change which fragments are pruned. It does change how readable the tree is and how cheaply a person or tool can list a single top-level slice.
Exercise
A dataset is partitioned by year and country in Hive layout. You run dataset.to_table(filter=ds.field("amount") > 100). Does partition pruning skip any files, and what can still reduce the work?
Show answer
No files are skipped by partition pruning, because amount is not a partition column and the directory names say nothing about its values. Work can still be reduced at the next levels. Parquet row group statistics (min and max of amount) can let the scanner skip row groups whose maximum is 100 or less, and the remaining rows are filtered after decoding. To get file-level pruning, the query would need a condition on year or country.
Exercise
You expect ds.field("year") == 2024 to keep one of four fragments, but get_fragments(filter=...) returns all four. Name two likely causes and how to check each.
Show answer
First, the partition field may not be named year or may not be typed as expected, for example if the dataset was opened without the Hive partitioning so the directory values were never exposed. Check dataset.schema and the partition_expression of each fragment. Second, the files may not follow the key=value layout, so they have no partition expression. Check the paths from dataset.files for stray or misnamed directories.