Sub topic 12
Processing larger-than-memory data in batches
This chapter assumes you can already write a partitioned dataset, open it with ds.dataset, and build filters with ds.field. It also assumes you know what a Parquet row group is. Here you will learn how to process data that does not fit in RAM by streaming it through a scanner one record batch at a time.
Why `to_table` is the wrong tool here
dataset.to_table() reads every selected row into one in-memory Arrow table. That works for a few gigabytes, but it fails once the filtered result exceeds available memory. Filters and column selection shrink the result, but they do not change the basic rule: a table holds all of its rows at once.
A record batch is a chunk of rows with a fixed schema. A scanner can produce batches one after another, so your program holds only a few at a time. Memory use then depends on batch size, not dataset size.
| Method | What it holds in memory | Typical use |
|---|---|---|
| `dataset.to_table()` | The whole result | Small or heavily filtered data |
| `scanner.to_batches()` | One batch, plus readahead | Python loops that aggregate |
| `scanner.to_reader()` | One batch, plus readahead | Passing a stream to a writer or another library |
| `scanner.count_rows()` | Almost nothing | Counting without loading values |
The streaming loop
Create a scanner with the filter and columns you need, then iterate over to_batches(). The filter prunes partition directories and the projection skips unneeded column chunks, as in the earlier chapters. Streaming adds to that, because the surviving data is delivered in pieces.
import pyarrow.dataset as ds
dataset = ds.dataset("sales", format="parquet", partitioning="hive")
scanner = dataset.scanner(
filter=ds.field("year") >= 2023,
columns=["country", "amount"],
)
total = 0.0
rows = 0
for batch in scanner.to_batches():
rows += batch.num_rows
total += sum(v for v in batch.column("amount").to_pylist() if v is not None)
print(rows, total)to_batches() is a generator. Each batch is released once your loop moves on and nothing else references it. If you append batches to a list, you rebuild the full table in memory and lose the benefit.
Where the memory goes
Memory is roughly batch_size × bytes per row × batches in flight. Three things set those numbers.
- Batch size. The
batch_sizeargument sets the maximum rows per batch. Recent PyArrow releases default to 131,072 rows, but older versions used larger values, so check your version. Wide rows with large strings or binary data need a smaller value. - Readahead. To keep the CPU and disk busy, the scanner reads ahead.
batch_readaheadcontrols how many batches are prefetched per fragment, andfragment_readaheadcontrols how many files are opened at once. Lowering both reduces peak memory at the cost of throughput. - Row group size. Parquet is decoded one row group column chunk at a time. A file written with a single 4 GB row group cannot be decoded in small pieces, however small you make
batch_size. This is why the writing chapters recommend moderate row group sizes.
import pyarrow.dataset as ds
dataset = ds.dataset("sales", format="parquet", partitioning="hive")
scanner = dataset.scanner(
columns=["country", "amount"],
batch_size=64_000,
batch_readahead=4,
fragment_readahead=2,
)
print(sum(b.num_rows for b in scanner.to_batches()))Aggregating with compute functions
Looping over to_pylist() is simple but slow for large batches, because it converts Arrow values to Python objects. Arrow's own functions work on whole columns without that conversion. A per-batch aggregate, merged into a running result, is the standard pattern.
from collections import defaultdict
import pyarrow as pa
import pyarrow.dataset as ds
dataset = ds.dataset("sales", format="parquet", partitioning="hive")
scanner = dataset.scanner(
filter=ds.field("year") >= 2023,
columns=["country", "amount"],
batch_size=64_000,
)
totals = defaultdict(float)
for batch in scanner.to_batches():
partial = (
pa.Table.from_batches([batch])
.group_by("country")
.aggregate([("amount", "sum")])
)
for country, subtotal in zip(
partial["country"].to_pylist(), partial["amount_sum"].to_pylist()
):
if subtotal is not None:
totals[country] += subtotal
print(dict(totals))This works because sums are decomposable. You can sum each batch and then sum the partial sums. Counts, minimums, maximums and sums share this property. A mean needs a running sum and a running count. A median or an exact distinct count does not decompose this way, so those need a different approach, such as a sketch or an engine that spills to disk.
Streaming into a writer
Sometimes the output is itself too large for memory, for example when you filter a big dataset and write the result under a new layout. scanner.to_reader() returns a RecordBatchReader, and ds.write_dataset accepts a reader directly. The data flows from the source files to the destination files without becoming a table.
import pyarrow.dataset as ds
dataset = ds.dataset("sales", format="parquet", partitioning="hive")
scanner = dataset.scanner(
filter=ds.field("year") >= 2023,
columns=["year", "country", "amount"],
)
ds.write_dataset(
scanner.to_reader(),
"sales_recent",
format="parquet",
partitioning=["country"],
partitioning_flavor="hive",
existing_data_behavior="overwrite_or_ignore",
)The scanner must include any column you partition by, because the writer needs its values to choose a directory. Here country is in the projection. The writer still buffers rows per open partition until it can emit a file or row group, so a high-cardinality partition column can raise memory use. The max_open_files option limits that.
Counting and peeking without loading everything
Not every question needs a full scan.
scanner.count_rows()counts matching rows. For filters that touch only partition columns, it can answer from file metadata and avoid reading data pages.scanner.head(n)returns the firstnrows as a table and stops early.dataset.take(indices)fetches specific row positions, but it is expensive on many files. Do not use it as a general lookup.
import pyarrow.dataset as ds
dataset = ds.dataset("sales", format="parquet", partitioning="hive")
scanner = dataset.scanner(filter=ds.field("country") == "DE")
print(scanner.count_rows())
print(scanner.head(2).to_pydict())Common errors
- Calling
to_table()"just to check". On a large dataset this is what causes the out-of-memory crash. Useheadorcount_rowsinstead. - Collecting batches in a list. A list of every batch is a table in disguise. Aggregate inside the loop.
- Iterating a reader twice. A
RecordBatchReaderis a one-shot stream. After it is consumed, it yields nothing. Create a new scanner or reader if you need a second pass. - Ignoring row group size. If memory stays high with a small
batch_size, inspect the source files. Huge row groups set a floor on memory use. - Unstable batch boundaries. Batches may be smaller than
batch_size, particularly at file or row group ends. Never assume a batch holds exactly that many rows. - Row order. Batches from different files can arrive in a different order than their file names suggest, because scanning is parallel. If order matters, sort afterwards or check the scanner's ordering options for your version.
Exercise
You scan a 200 GB partitioned dataset and your loop does batches = list(scanner.to_batches()) before computing a sum. The process runs out of memory even though the scanner has a filter and a two-column projection. Explain why, and show the loop body that fixes it.
Show answer
list(...) keeps every batch alive, so the full filtered result sits in memory, the same as to_table(). Aggregate inside the loop and keep only a running value, for example total = 0.0 before the loop and total += pc.sum(batch.column("amount")).as_py() or 0.0 inside it, with import pyarrow.compute as pc. Each batch can then be freed after its iteration, so memory stays near the size of a few batches.
Exercise
You lower batch_size to 1,000 rows, but peak memory barely changes. The source Parquet files each contain one row group of several gigabytes. What is the likely cause, and what would you change?
Show answer
Parquet column chunks are decoded per row group, so a single huge row group must be read and decoded largely at once regardless of batch_size. The fix is on the writing side: rewrite the data with smaller row groups, using max_rows_per_group and min_rows_per_group in ds.write_dataset. You can do this with a streaming copy from scanner.to_reader().