Sub topic 3
From files to a dataset: datasets and fragments
This chapter assumes you know basic Python, can read a table schema, and know that a Parquet file stores columns in row groups. The previous chapters covered Arrow tables and the Parquet layout. Here we look at how PyArrow treats many files as one table.
Why a dataset exists
pyarrow.parquet.read_table on one file is simple. Real data usually arrives as many files: one per day, one per job, one per writer thread. You could read each file, then concatenate the tables. That loads everything into memory and gives you no way to skip files.
A dataset is PyArrow's answer. It is a lazy description of a collection of files that behaves like one logical table. Creating a dataset reads almost no data. It lists files and reads schema metadata. Rows are only read when you ask for them.
The two objects: dataset and fragment
Two objects matter in pyarrow.dataset.
- A dataset (
ds.Dataset) is the whole collection. It has one schema and a list of fragments. - A fragment is one piece of the dataset. For Parquet, a fragment is normally one file. A fragment can be split further into one fragment per row group.
A dataset does not hold data. It holds enough information to build a scanner, the object that reads the data. Filters and column selection are applied when you scan. Later chapters cover scanners in detail.
Building a small dataset to inspect
The script below writes four Parquet files into a temporary directory. The third file uses a small row group size, and the fourth has an extra column. We will use these differences to see how a dataset behaves.
import tempfile
from pathlib import Path
import pyarrow as pa
import pyarrow.dataset as ds
import pyarrow.parquet as pq
root = Path(tempfile.mkdtemp()) / "events"
root.mkdir()
pq.write_table(pa.table({"id": [1, 2, 3], "value": [0.5, 1.5, 2.5]}),
root / "a.parquet")
pq.write_table(pa.table({"id": [4, 5], "value": [3.5, 4.5]}),
root / "b.parquet")
pq.write_table(pa.table({"id": [6, 7, 8, 9], "value": [5.5, 6.5, 7.5, 8.5]}),
root / "c.parquet", row_group_size=2)
pq.write_table(pa.table({"id": [10], "value": [9.5], "note": ["late"]}),
root / "d.parquet")
dataset = ds.dataset(str(root), format="parquet")
print(dataset.schema)
print([Path(f).name for f in sorted(dataset.files)])
print(dataset.count_rows())The output is:
id: int64
value: double
['a.parquet', 'b.parquet', 'c.parquet', 'd.parquet']
10ds.dataset walked the directory, found four files, and built a dataset. count_rows() answers from Parquet footer metadata where it can, so it does not need to decode the column data.
Notice that note is missing from the schema. The next section explains why.
Where the dataset schema comes from
A dataset has exactly one schema, and every fragment is presented through it. By default, PyArrow inspects only the first file it discovers and uses that file's schema. Here that was a.parquet, so note from d.parquet was dropped without any error.
You can supply the schema yourself:
schema = pa.schema([
("id", pa.int64()),
("value", pa.float64()),
("note", pa.string()),
])
full = ds.dataset(str(root), format="parquet", schema=schema)
print(full.to_table().column("note").to_pylist())The output is:
[None, None, None, None, None, None, None, None, None, 'late']Files that lack a column in the dataset schema are read with that column filled with nulls. Files whose columns have incompatible types raise an error when scanned, not when the dataset is created. Creation is cheap and lazy, so schema problems can appear late.
Inspecting fragments
Iterate over get_fragments() to see how the dataset is divided:
for fragment in dataset.get_fragments():
meta = fragment.metadata
print(Path(fragment.path).name, meta.num_rows, meta.num_row_groups)The output is:
a.parquet 3 1
b.parquet 2 1
c.parquet 4 2
d.parquet 1 1Each fragment here is a ParquetFileFragment. Its metadata attribute is the Parquet footer, which the fragment reads on first access. The footer lists row counts and, per column chunk, statistics such as minimum and maximum values. Those statistics let a scanner skip row groups that cannot match a filter, which you will use in the pruning chapter.
You can also split a fragment by row group:
c_fragment = [f for f in dataset.get_fragments()
if f.path.endswith("c.parquet")][0]
for piece in c_fragment.split_by_row_group():
print(piece.row_groups[0].id, piece.count_rows())The output is:
0 2
1 2This is useful for parallel work: each piece can be handed to a different worker.
Ways to create a dataset
ds.dataset accepts several kinds of source.
| Source | Result | Notes |
|---|---|---|
| A directory path | Dataset over all files found recursively | The most common form |
| A single file path | Dataset with one fragment | Same API as a directory |
| A list of file paths | Dataset over exactly those files | No directory walk |
| A `pa.Table` or list of tables | In-memory dataset | Same scanning API, no files |
For a list of paths, only the listed files are used. This is a way to read a chosen subset of a directory.
What discovery skips
When walking a directory, PyArrow ignores files whose names start with . or _. These are typically hidden files, _SUCCESS markers, or _metadata files written by other tools.
Other files, such as .csv or .txt files in the same directory, are not ignored. They are treated as Parquet files and will fail when scanned. Keep non-data files out of dataset directories, or pass an explicit list of paths.
Dataset versus reading one file
| Task | `pq.read_table` on one file | `ds.dataset` |
|---|---|---|
| Many files, one schema | Manual loop | Built in |
| Skip files by filter | No | Yes |
| Stream in batches | Limited | Yes, through scanners |
| Other formats (CSV, Feather) | No | Yes, through `format=` |
Common errors at this stage
- A missing column. The first file defined the schema. Pass
schema=. ArrowInvalidwhen scanning. One file has a column type that cannot be cast to the dataset schema. Find it by scanning fragment by fragment.- Fewer files than expected. Check the ignored prefixes and the path you passed.
- Slow creation on remote storage. Listing millions of objects is the cost. Pass a list of paths if you already know them.
Exercise
A directory has three Parquet files. Only the last one contains a column region. You call ds.dataset(path, format="parquet") and region is not in dataset.schema. Why, and how do you fix it?
Show answer
By default the dataset schema is taken from the first discovered file, which lacks region, so the column is dropped. Fix it by passing schema= with region included. Files without the column then return nulls for it.
Exercise
How can you find out how many row groups each file in a dataset has, without reading any column data?
Show answer
Loop over dataset.get_fragments() and read fragment.metadata.num_row_groups. This uses the Parquet footer only.