Sub topic 12
Scanning datasets with filters and column projection
This chapter assumes you can run pyarrow code, know what a Parquet file is, and have read the earlier chapters on tables and on Arrow and Parquet. It shows how to read only the rows and columns you need from many files.
Why scan instead of load
pq.read_table loads whole files. That is fine for small data. For a directory of many files, most of the cost is reading bytes you will throw away.
A dataset is a lazy description of a set of files. Creating one reads file metadata, not the data. The data is read when you ask for a result, and two options shrink what is read:
- Column projection reads only the columns you list.
- Filter (also called a predicate) keeps only rows that match a condition.
A first scan
The code below writes a small Parquet file and then scans it.
import os
import pyarrow as pa
import pyarrow.dataset as ds
import pyarrow.parquet as pq
os.makedirs("data", exist_ok=True)
source = pa.table({
"id": [1, 2, 3, 4],
"name": ["a", "b", "c", "d"],
"score": [0.5, 1.5, 2.5, 3.5],
})
pq.write_table(source, "data/part-0.parquet")
dataset = ds.dataset("data/", format="parquet")
table = dataset.to_table(
columns=["id", "name"],
filter=ds.field("id") > 1,
)
print(table.num_rows)
print(table.column_names)The output is 3 and ['id', 'name']. The score column was never read from disk. The filter is applied during the scan, so rows with id of 1 never reach your table.
How the scan works
Parquet files store min and max statistics for each row group, which is a block of rows. If a row group's maximum id is 1, the filter id > 1 cannot match, so that block is skipped. This skipping is an optimization. The filter is always applied to the remaining rows, so the result is the same as filtering after a full load.
Writing filters
Filters are expressions, not Python booleans. Build them with ds.field, then combine them with operators.
import pyarrow.dataset as ds
expr = (ds.field("id") > 1) & (ds.field("name") != "d")
dataset = ds.dataset("data/", format="parquet")
print(dataset.to_table(filter=expr).num_rows)Use &, | and ~ for and, or and not. Python's and and or raise an error, because an expression has no single true or false value. Wrap each comparison in parentheses, since & binds more tightly than >.
Streaming large results
to_table builds the whole result in memory. If the filtered result is still large, use a scanner and process record batches one at a time.
import pyarrow.dataset as ds
dataset = ds.dataset("data/", format="parquet")
scanner = dataset.scanner(columns=["id"], filter=ds.field("id") > 1)
total = 0
for batch in scanner.to_batches():
total += batch.num_rows
print(total)Only one batch at a time needs to be held, so memory use stays bounded.
Common errors
- Unknown column name. Naming a column that is not in the dataset schema raises an error. Check
dataset.schemafirst. - Type mismatch. Comparing an integer column with a string fails. Use a value of the column's type.
- Expecting a filter to speed up everything. Skipping only works when statistics can rule out a row group. A filter on unsorted data may skip nothing, though it still returns the right rows.
- Forgetting that projection is by name. Columns come back in the order you list them in
columns.
Exercise
You want the name values for rows where score is at least 2 from a Parquet dataset. Which columns and filter arguments do you pass to to_table, and does score have to be in columns?
Show answer
Pass columns=["name"] and filter=ds.field("score") >= 2. score does not need to be in columns, because the filter is evaluated during the scan and the projection only controls which columns appear in the result.