Sub topic 3
From files to a dataset: datasets and fragments
This chapter assumes you know basic Python, have seen a Parquet file, and can build an Arrow table with a schema. The goal is to see how PyArrow turns a directory of files into one logical table.
Why a dataset
Data often arrives as many files: one per day, per job, or per partition. Reading them with pq.read_table one by one means writing your own loop and combining the results by hand. A dataset (pyarrow.dataset.Dataset) is an object that represents all those files as one table, without reading them up front.
The two pieces
- A dataset is the whole collection. It has a single schema and a list of files.
- A fragment is one piece of a dataset, usually one file. For Parquet, it is a
ParquetFileFragment.
Scanning a dataset means scanning its fragments and joining the results. Later chapters rely on this. Filters can skip a whole fragment, and batches stream out one fragment at a time.
Opening a dataset
The following code writes two small files and opens the directory as a dataset.
import os
import pyarrow as pa
import pyarrow.dataset as ds
import pyarrow.parquet as pq
os.makedirs("events", exist_ok=True)
pq.write_table(pa.table({"id": [1, 2, 3], "value": [0.5, 1.5, 2.5]}),
"events/part-0.parquet")
pq.write_table(pa.table({"id": [4, 5], "value": [3.5, 4.5]}),
"events/part-1.parquet")
dataset = ds.dataset("events", format="parquet")
print(dataset.schema)
print(sorted(dataset.files))
for fragment in dataset.get_fragments():
print(fragment.path, fragment.count_rows())
print(dataset.count_rows())ds.dataset walks the directory and lists the files. Reading the footer of a Parquet file gives its schema and row count without loading the data. count_rows() uses that metadata, so it is cheap. The call returns quickly because the dataset is lazy. Data is only read when you call to_table() or use a scanner.
How the schema is chosen
By default, PyArrow infers the dataset schema from the first file it finds. It does not compare the other files. If a later file has a different column type or a missing column, you usually find out when you read that file, not when you open the dataset.
To avoid this, pass a schema yourself:
schema = pa.schema([("id", pa.int64()), ("value", pa.float64())])
dataset = ds.dataset("events", format="parquet", schema=schema)Files are then read against this schema. Columns missing from a file come back as nulls, and extra columns are ignored.
Exercise
You open a directory of 100 Parquet files with ds.dataset and no schema argument. The 100th file stores "id" as a string, while the first file stores it as int64. When is the problem most likely to show up, and how do you prevent it?
Show answer
It shows up when a scan reaches the 100th file, not when the dataset is opened, because the schema was inferred from the first file only. To prevent it, pass an explicit schema to ds.dataset so every file is read against the same types.