Sub topic 15
Choosing partition keys and avoiding small files
This chapter assumes you can write and read a Hive-partitioned Parquet dataset with ds.write_dataset and ds.dataset. It also assumes you know that a filter on a partition column lets PyArrow skip whole directories. Here you decide which columns to partition on and how to keep the file count under control.
Why the choice matters
Every partition value becomes a directory, and every directory holds at least one file. Each file has a cost. PyArrow must list it, open it, and read its Parquet footer before it can scan anything. On local disks this overhead is small. On object stores such as S3, each file adds at least one network request, so many tiny files can dominate the runtime.
Partitioning has two opposite failure modes:
- Too coarse. A filter cannot skip much, so queries read far more data than they need.
- Too fine. The dataset has thousands of tiny files. Listing and opening them costs more than reading the data.
Criteria for a good partition key
A good key meets these conditions:
- Queries filter on it. If no query filters on a column, partitioning by it only adds directories.
- It has low or moderate cardinality. Cardinality is the number of distinct values. Tens to a few thousand partitions is a workable range.
- Values are spread fairly evenly. One partition holding 90% of the rows gives you one huge file and many tiny ones.
- Values stop changing once written. A date from the event itself is stable. A "status" column that gets updated is not.
| Column | Cardinality | Typical verdict |
|---|---|---|
| `year`, `month` | Low | Good, if queries filter by time |
| `country` | Low to moderate | Good, if queries filter by it |
| `event_date` (daily) | Moderate, grows over time | Good for long-lived data, but watch the file count |
| `user_id`, `order_id` | High | Poor: millions of directories |
| `timestamp` | Very high | Never partition on it directly |
For a high-cardinality column such as user_id, do not partition. Instead, sort the data by that column before writing. Each Parquet row group stores minimum and maximum statistics for each column. Sorted data gives each row group a narrow range, so a filter on user_id can skip row groups.
Seeing the cost: file counts by key
The next script writes the same table twice, once partitioned by a low-cardinality column and once by a high-cardinality column. It then counts the files in each result.
import tempfile
from pathlib import Path
import pyarrow as pa
import pyarrow.dataset as ds
n = 10_000
table = pa.table({
"user_id": pa.array([i % 1000 for i in range(n)], pa.int64()),
"month": pa.array([1 + (i % 12) for i in range(n)], pa.int8()),
"amount": pa.array([float(i) for i in range(n)]),
})
def count_files(root):
return sum(1 for _ in Path(root).rglob("*.parquet"))
with tempfile.TemporaryDirectory() as tmp:
for key in ("month", "user_id"):
out = Path(tmp) / key
ds.write_dataset(
table,
str(out),
format="parquet",
partitioning=[key],
partitioning_flavor="hive",
)
print(key, count_files(out))
# month 12
# user_id 1000The same 10,000 rows produce 12 files in one layout and 1,000 files of about 10 rows each in the other. write_dataset also has a max_partitions argument, which defaults to 1024. A write that would create more partitions than that fails with an error. Treat the error as a signal that the key is wrong, not as a limit to raise.
Deriving a coarser key
Often the raw column is too fine, but a derived column works well. Compute it with pyarrow.compute and add it to the table before writing.
import tempfile
from datetime import datetime
import pyarrow as pa
import pyarrow.compute as pc
import pyarrow.dataset as ds
table = pa.table({
"ts": pa.array(
[datetime(2023, 12, 31, 23, 0), datetime(2024, 1, 1, 8, 30),
datetime(2024, 1, 15, 12, 0), datetime(2024, 2, 2, 9, 45)],
pa.timestamp("us"),
),
"amount": [1.0, 2.0, 3.0, 4.0],
})
table = table.append_column("year", pc.year(table["ts"]))
table = table.append_column("month", pc.month(table["ts"]))
with tempfile.TemporaryDirectory() as tmp:
ds.write_dataset(
table,
tmp,
format="parquet",
partitioning=["year", "month"],
partitioning_flavor="hive",
)
dataset = ds.dataset(tmp, format="parquet", partitioning="hive")
print(sorted(f.split("/")[-3:-1] for f in dataset.files))The original ts column stays in the data files. Queries can still filter on ts for fine-grained selection, and the year and month filters skip whole directories first.
File sizing guidance
Partitioning multiplies the number of files. If each partition receives only a little data, you get many small files. As a rule of thumb:
- Aim for files of roughly 100 MB to 1 GB on disk.
- Aim for row groups of roughly 100,000 to 1,000,000 rows. Smaller groups weaken compression and add metadata. Larger groups use more memory per scan thread.
- Estimate the files per partition as
partition size / target file size. If that is well below 1, the key is too fine.
You control this on write with max_rows_per_file, min_rows_per_group and max_rows_per_group. These options only cap or group rows. They cannot merge data across partitions, so a partition with 50 rows still gets its own file.
How small files appear in practice
The most common source is not a bad key but repeated appends. Each call to write_dataset into an existing dataset adds new files to every partition it touches. A job that runs every few minutes and writes a handful of rows per partition leaves thousands of tiny files after a few days.
The usual fix is compaction: read the fragmented dataset and rewrite it into a new location with larger files.
import tempfile
from pathlib import Path
import pyarrow as pa
import pyarrow.dataset as ds
def count_files(root):
return sum(1 for _ in Path(root).rglob("*.parquet"))
with tempfile.TemporaryDirectory() as tmp:
small = str(Path(tmp) / "events_small")
compact = str(Path(tmp) / "events_compact")
# Simulate 20 small appends into the same partition.
for i in range(20):
batch = pa.table({
"day": pa.array(["2024-01-01"] * 50, pa.string()),
"value": pa.array(list(range(i * 50, (i + 1) * 50)), pa.int64()),
})
ds.write_dataset(
batch,
small,
format="parquet",
partitioning=["day"],
partitioning_flavor="hive",
basename_template=f"batch{i}-{{i}}.parquet",
existing_data_behavior="overwrite_or_ignore",
)
src = ds.dataset(small, format="parquet", partitioning="hive")
ds.write_dataset(
src,
compact,
format="parquet",
partitioning=["day"],
partitioning_flavor="hive",
max_rows_per_file=1_000_000,
max_rows_per_group=1_000_000,
)
print(count_files(small), "->", count_files(compact))
# 20 -> 1The basename_template includes a batch number so that each append writes uniquely named files. Without it, every append would try to write part-0.parquet and overwrite the previous one.
The compacted data goes to a new directory. Do not rewrite a dataset in place while reading from it, because the scan may see files that are being replaced.
Common mistakes
- Partitioning by an ID column. You get one directory per value and files of a few rows each.
- Partitioning by many columns at once. Cardinalities multiply. Three keys with 10, 50 and 365 values give up to 182,500 directories.
- Partitioning on a column nobody filters on. It adds file overhead and gives no pruning benefit.
- Skewed keys. One dominant value, such as a single large country, leaves a few huge files next to many tiny ones. Consider a different or coarser key.
- Changing the key later. Existing data must be rewritten to a new layout, so check your most common query filters before you commit.
Checking what you built
After any write, count the files and look at their sizes. If the median file is under a few megabytes, revisit the key or add a compaction step.
Exercise
A table of web logs has 500 million rows per day, with columns request_id (unique), status_code (about 10 distinct values), event_date, and hour (0 to 23). Most queries filter on a date range and sometimes on a single hour. Which columns would you partition on, and what would you do about request_id?
Show answer
Partition on event_date and possibly hour. At 500 million rows per day, each hour still holds about 20 million rows, which is enough for full-sized files, so the extra directory level is worth it. status_code is low cardinality but only worth including if queries commonly filter on it. Never partition on request_id, because it is unique and would create one directory per row. If lookups by request_id matter, sort the data by it within each partition so row group statistics let the scanner skip row groups.