Sub topic 7
Writing a partitioned dataset with write_dataset
This chapter assumes you can build a pyarrow.Table, know what a Parquet file is, and have seen the Hive directory layout (year=2023/country=DE/). You will learn how ds.write_dataset turns one table into a tree of files, which arguments control that tree, and how to avoid the common write-time mistakes.
What write_dataset does
ds.write_dataset takes data, a destination, a file format, and a partitioning. It splits the rows by the values of the partition columns and writes each group into its own directory. It can write more than one file per directory, depending on your size limits.
The data argument can be any of these:
- a
TableorRecordBatch - a
DatasetorScanner - an iterable of record batches (you must also pass
schema=)
Accepting a scanner or dataset means you can repartition data without loading it all into memory. Section "Repartitioning an existing dataset" shows this.
A basic Hive-partitioned write
The partitioning object says which columns become directories and what type each has.
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",
)
# Creates paths such as sales/year=2023/country=DE/part-0.parquetThe order of fields in the partitioning schema sets the directory nesting. Here year is the outer level and country is the inner one. Put the column you filter on most often first.
The partition columns are removed from the files. The value 2023 exists only in the directory name year=2023. When you read the dataset back with the same partitioning, PyArrow rebuilds the columns from the paths. If you read a single file directly, those columns are missing.
Shorthand: a list of column names
If the default types are acceptable, pass column names and a flavor:
ds.write_dataset(
table,
"sales_short",
format="parquet",
partitioning=["year", "country"],
partitioning_flavor="hive",
)With this form, PyArrow takes the field types from the table's own schema. Use an explicit ds.partitioning(schema, ...) object when you want to pin the types yourself, as in the first example. Without partitioning_flavor="hive", the list form writes directory partitioning, where directories hold only values such as 2023/DE/.
Key arguments
| Argument | Default | Purpose |
|---|---|---|
| `base_dir` | required | Root directory (or URI prefix) of the dataset |
| `format` | required | `"parquet"`, `"ipc"`, `"csv"`, or a format object |
| `partitioning` | none | A partitioning object or a list of column names |
| `partitioning_flavor` | none | `"hive"` or none, used with a list of names |
| `basename_template` | `part-{i}.parquet` for Parquet | File name pattern. `{i}` is replaced by a counter. |
| `max_partitions` | 1024 | Maximum number of partition directories in one write |
| `max_open_files` | 1024 | Maximum number of files open at once |
| `max_rows_per_file` | 0 (unlimited) | Start a new file after this many rows |
| `min_rows_per_group` | 0 | Buffer rows until a row group has at least this many |
| `max_rows_per_group` | 1048576 | Upper limit on rows in one row group |
| `existing_data_behavior` | `"error"` | What to do if the target already has data |
| `file_visitor` | none | Callback invoked for each file written |
Two limits cause failures on real data. If your data would create more than max_partitions directories, the write raises an error. Raise max_partitions only after asking whether that many directories is a good design (see the chapter on choosing partition keys). If the data touches more directories than max_open_files, PyArrow closes writers as needed. Very low values can produce many small files.
Controlling file and row group size
Row group size affects read performance, because Parquet readers skip and decode whole row groups. File size affects how many files a reader must open.
import pyarrow as pa
import pyarrow.dataset as ds
table = pa.table({
"year": [2023, 2023, 2024],
"amount": [1.0, 2.0, 3.0],
})
ds.write_dataset(
table,
"sales_tuned",
format="parquet",
partitioning=["year"],
partitioning_flavor="hive",
max_rows_per_file=1_000_000,
min_rows_per_group=100_000,
max_rows_per_group=1_000_000,
max_open_files=512,
existing_data_behavior="delete_matching",
)With these settings, each file holds at most one million rows. Each row group holds between 100,000 and 1,000,000 rows, except that the last group of a file may be smaller. The data here is tiny, so you will still get one file per year. The limits only matter when a partition has more rows than the limit.
Handling existing data
existing_data_behavior decides what happens when the destination already contains files.
| Value | Behavior |
|---|---|
| `"error"` | Raise an error if the destination directory is non-empty. This is the default and the safest choice. |
| `"overwrite_or_ignore"` | Write new files. A file whose name matches an existing file replaces it. Other existing files are left alone. |
| `"delete_matching"` | Before writing, delete everything inside each partition directory that this write will touch. Directories not touched are left alone. |
Appending without overwriting
"overwrite_or_ignore" does not mean "append". With the default basename_template, every write produces part-0.parquet in each directory. A second write replaces the first write's file, and you lose rows. To append, give each write a unique file name:
import uuid
import pyarrow as pa
import pyarrow.dataset as ds
new_rows = pa.table({
"year": [2024],
"country": ["DE"],
"amount": [99.0],
})
part = ds.partitioning(
pa.schema([("year", pa.int64()), ("country", pa.string())]),
flavor="hive",
)
ds.write_dataset(
new_rows,
"sales",
format="parquet",
partitioning=part,
basename_template=f"part-{uuid.uuid4().hex}-{{i}}.parquet",
existing_data_behavior="overwrite_or_ignore",
)The doubled braces {{i}} keep a literal {i} in the f-string, so PyArrow can still substitute its counter.
Replacing a partition
Use "delete_matching" to replace only the partitions present in the new data. If you write rows for year=2024 and country=DE, only that directory is cleared first. Other partitions stay unchanged. Be careful: the delete happens inside the same call, and a failure partway through can leave a partition empty or partly written. The dataset API does not give you transactions.
Tracking what was written
Pass file_visitor to learn which files were created. This is useful for logging or building a manifest.
import pyarrow as pa
import pyarrow.dataset as ds
table = pa.table({"year": [2023, 2024], "amount": [1.0, 2.0]})
written = []
def visit(written_file):
written.append((written_file.path, written_file.metadata.num_rows))
ds.write_dataset(
table,
"sales_visited",
format="parquet",
partitioning=["year"],
partitioning_flavor="hive",
file_visitor=visit,
existing_data_behavior="overwrite_or_ignore",
)
for path, rows in sorted(written):
print(path, rows)The metadata attribute holds the Parquet file metadata, so you can read row counts and statistics without reopening the file.
Repartitioning an existing dataset
Because data can be a dataset, you can change the layout of existing data. Open the source and write it with new partitioning. PyArrow streams batches from the scanner, so the full dataset need not fit in memory.
import pyarrow.dataset as ds
source = ds.dataset("sales", format="parquet", partitioning="hive")
ds.write_dataset(
source,
"sales_by_country",
format="parquet",
partitioning=["country"],
partitioning_flavor="hive",
existing_data_behavior="overwrite_or_ignore",
)Write to a new directory. Writing into the directory you are reading from can mix old and new files during the scan.
Directory partitioning on write
Directory partitioning omits the name= part, so paths look like sales_dir/2023/part-0.parquet.
import pyarrow as pa
import pyarrow.dataset as ds
table = pa.table({"year": [2023, 2024], "amount": [1.0, 2.0]})
ds.write_dataset(
table,
"sales_dir",
format="parquet",
partitioning=ds.partitioning(pa.schema([("year", pa.int16())])),
)
dataset = ds.dataset(
"sales_dir",
format="parquet",
partitioning=ds.partitioning(pa.schema([("year", pa.int16())])),
)
print(dataset.to_table().schema)The reader needs the same schema, because nothing in the path names the field or gives its type.
Common write-time mistakes
- Running a write twice with the default
"error"setting fails on the second run. Choose a behavior on purpose. - Using
"overwrite_or_ignore"with the default file name silently replaces files. Use a uniquebasename_templateto append. - Partitioning on a high-cardinality column such as a user ID creates thousands of directories with tiny files, and can trip
max_partitions. - Reading with a different partition schema than you wrote with changes the column types or fails.
Exercise
You call writedataset twice with the same one-row table, partitioning=["year"], partitioningflavor="hive", and existingdatabehavior="overwriteorignore". You expect two rows when you read the dataset, but you get one. Why, and how do you fix it?
Show answer
Both calls write year=<value>/part-0.parquet, because the default basenametemplate is part-{i}.parquet. The second call overwrites the first file. Fix it by passing a unique basenametemplate per write, for example f"part-{uuid.uuid4().hex}-{{i}}.parquet".
Exercise
You want to replace the data for year=2024 only, leaving year=2023 untouched. Which existingdatabehavior do you use, and what is the risk?
Show answer
Use "delete_matching" and write a table that contains only year=2024 rows. It clears each partition directory being written to, so 2023 stays. The risk is that the delete and write are not atomic, so a failure can leave the 2024 partition empty or incomplete, and the call also removes any other files in that directory.