Sub topic 14
Appending, overwriting and deleting existing data
This chapter assumes you can call ds.write_dataset with a partitioning, and that you know a Hive-partitioned dataset is a directory tree such as sales/year=2023/part-0.parquet. Here you will learn what happens when you write to a location that already holds data.
Why existing data needs a policy
ds.write_dataset writes files. It does not manage a table. The Parquet files already in the target directory are plain files, and PyArrow has no catalog or transaction log that knows which ones belong to "the table".
So write_dataset needs a rule for files that are already there. You set that rule with the existing_data_behavior argument. It accepts three values.
| Value | What it does | Typical use |
|---|---|---|
| `"error"` (default) | Raises an error if the destination already contains data | First load, protection against accidents |
| `"overwrite_or_ignore"` | Leaves existing files alone. Replaces a file only if the new output has the same file name | Appending, or replacing files by name |
| `"delete_matching"` | Deletes everything in each partition directory that this write touches, then writes | Replacing whole partitions |
The default: error
With the default, writing a second time into a non-empty destination fails. The check is on the destination, not on whether the rows overlap.
import tempfile
from pathlib import Path
import pyarrow as pa
import pyarrow.dataset as ds
base = str(Path(tempfile.mkdtemp()) / "sales")
batch1 = pa.table({
"year": [2023, 2023, 2024],
"amount": [1.0, 2.0, 3.0],
})
def write(table, **kwargs):
ds.write_dataset(
table,
base,
format="parquet",
partitioning=["year"],
partitioning_flavor="hive",
**kwargs,
)
def count():
dataset = ds.dataset(base, format="parquet", partitioning="hive")
return dataset.count_rows()
write(batch1)
print("after first write:", count())
try:
write(batch1)
except pa.ArrowInvalid as exc:
print("second write refused:", type(exc).__name__)The first write succeeds and count() returns 3. The second write raises ArrowInvalid, and no files change.
Overwrite by file name
"overwrite_or_ignore" does not mean "overwrite the partition". It means PyArrow will not complain about existing files, and it will replace a file only when the new output has the same path.
The default basename_template is part-{i}.parquet. Here {i} is a counter that starts at 0 on every call. Two calls with the default template therefore both try to write part-0.parquet in each partition directory. The second call replaces the first call's file, so no rows are added.
write(batch1, existing_data_behavior="overwrite_or_ignore")
print("same names, rows:", count()) # still 3This gives you an idempotent re-run: running the same job twice leaves the same data. It is also a trap if you meant to append. The new data silently replaces the old data whenever the file names collide.
Appending with unique file names
To append, give each write run its own file names. Put a unique token in basename_template. The template must contain {i}.
import uuid
batch2 = pa.table({"year": [2024], "amount": [4.0]})
run_id = uuid.uuid4().hex
write(
batch2,
basename_template=f"run-{run_id}-{{i}}.parquet",
existing_data_behavior="overwrite_or_ignore",
)
print("after append:", count()) # 4The double braces {{i}} in the f-string produce a literal {i} in the template. The new file lands in year=2024/ next to part-0.parquet, and the dataset now contains both files.
A run identifier such as a UUID, a timestamp, or a batch id from your scheduler also makes it easy to find which files a given run produced.
Replace partitions with delete_matching
"delete_matching" replaces data at partition granularity. For each partition directory that appears in the data being written, PyArrow deletes the directory's existing contents the first time it writes there. Directories for partitions that are not in the new data are never touched.
replacement = pa.table({"year": [2024, 2024], "amount": [10.0, 20.0]})
write(replacement, existing_data_behavior="delete_matching")
print("after replacing 2024:", count()) # 4: two from 2023, two new from 2024Both of the earlier 2024 files are gone, including the appended run-... file. The year=2023 directory is unchanged. This is the usual pattern for a daily or monthly reload: recompute one partition and replace it.
Edge cases
- Partitions absent from the new data.
delete_matchingonly deletes directories that the write actually creates. If you recompute March and the new table has no March rows, the old March directory stays, because nothing was written there. To delete a partition, remove its directory yourself with a file system call. - Empty input. Writing an empty table creates no partition directories, so
delete_matchingdeletes nothing. - Overlapping appends.
overwrite_or_ignorewith unique names never checks for duplicate rows. If a job is retried after a partial success, you get duplicates. Use a stable run id so a retry reuses the same file names, or usedelete_matchingfor idempotent reloads. - Stale files from an older layout. If you change the partition columns or the flavor, old directories remain. The reader will then discover two layouts under one root and fail or return confusing data. Write the new layout to a new root.
Removing data without writing
PyArrow's dataset API has no "delete rows where" operation. To remove a partition entirely, delete its directory with the file system object. The example below reuses base from the earlier code.
from pyarrow import fs
local = fs.LocalFileSystem()
local.delete_dir(f"{base}/year=2023")
print("after deleting 2023:", count()) # 2delete_dir removes the directory and everything inside it. Run it only on paths you have checked, because there is no undo. The same call works on S3FileSystem and other file system classes. On object stores, listing and deleting many small files is slow, which is one more reason to avoid tiny files.
To remove individual rows, read the affected partition, filter the rows out in memory, and write the partition back with delete_matching. This is safe only when the partition fits in memory and no one else writes to it at the same time.
Summary of decisions
- First load into an empty directory: keep the default
"error". - Add new rows and keep old files:
"overwrite_or_ignore"with a uniquebasename_template. - Re-run a job and get the same result:
"delete_matching"on the partitions the job owns. - Remove a partition: delete its directory yourself.
Exercise
A nightly job appends yesterday's rows to events/date=.../ using existing_data_behavior="overwrite_or_ignore" and the default basename_template. After a week, each day's partition holds only the rows of the last run for that date, and a late-arriving correction batch for an old date made earlier rows vanish. What causes this, and how do you change the job so that it appends instead?
Show answer
The default template part-{i}.parquet restarts at part-0.parquet on every call, so each run writes a file with the same name as the previous run's file in the same partition directory. overwrite_or_ignore replaces files with the same name, so the older rows are overwritten. To append, give each run a unique basename_template, for example f"run-{run_id}-{{i}}.parquet" with a UUID or scheduler batch id. If the intent is to rebuild a date from scratch, use delete_matching instead, with the full recomputed data for that date.