Sub topic 11
Keeping the final result small enough
Streaming bounds the memory used while a query runs. It does not bound the size of the result you ask for. This chapter assumes you know basic Polars expressions, scan_parquet, and collect(engine="streaming"). It covers how to keep the output small, or to avoid holding it in memory at all.
Why the result can still be too big
collect(engine="streaming") returns a normal in-memory DataFrame. The engine reads the input in chunks, but it appends every output row to that one DataFrame. If the query keeps most of the rows, the result is about as large as the input, and you hit the same out-of-memory error you had with eager loading.
Two queries over the same input show the difference:
- A
filterthat keeps 1% of rows gives a small result. - A
with_columnsthat keeps every row gives a result as big as the input, plus the new columns.
Reduce the result before collecting
Shrink the result inside the query, so the engine never builds the large version. These techniques are listed from most to least effective.
- Aggregate. Return one row per group instead of one row per event.
- Filter early. Keep only the rows you need.
- Select columns. Drop columns you do not use. Wide string columns cost the most.
- Limit rows. Use
headwhen you only need a sample.
import polars as pl
summary = (
pl.scan_parquet("events/*.parquet")
.filter(pl.col("status") == "ok")
.select("user_id", "amount")
.group_by("user_id")
.agg(pl.col("amount").sum().alias("total_amount"))
.collect(engine="streaming")
)
print(summary.shape)The result has one row per distinct user_id, not one row per event. The input can be far larger than memory as long as the number of distinct users fits.
Estimate the size before you collect
Check the size on a cheap version of the query before you collect the full one. Count the rows first. A count over a Parquet scan needs very little memory.
import polars as pl
lf = pl.scan_parquet("events/*.parquet").filter(pl.col("status") == "ok")
n_rows = lf.select(pl.len()).collect(engine="streaming").item()
print(f"rows after filter: {n_rows}")Multiply the row count by the approximate bytes per row to estimate the in-memory size. As a rough check, an Int64 column uses 8 bytes per row, and strings use more.
Send large results to disk
When you need every row, such as for a cleaned copy of the data, do not collect. Use a sink. sink_parquet writes each chunk to the file as it is produced, so memory use does not grow with the output.
import polars as pl
(
pl.scan_csv("events.csv")
.filter(pl.col("amount") > 0)
.sink_parquet("events_positive.parquet")
)You can then run a second, smaller query against the new file with scan_parquet.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Collecting a query with no filter or aggregation | Result as large as the input | Aggregate, filter, or sink |
| Calling `.collect()` just to print the data | Builds the whole result | Use `.head(10).collect()` |
| Keeping unused columns | Larger result | Add `select` |
| Aggregating on a high-cardinality key | Almost one output row per input row | Pick a coarser key or sink the output |
Exercise
A query scans 500 GB of Parquet files, adds a computed column to every row, and calls collect(engine="streaming"). It fails with an out-of-memory error. Name two ways to fix it.
Show answer
The result keeps every row, so it is larger than memory even though the engine reads in chunks. First, reduce the result inside the query with a filter, a groupby aggregation, or a select of fewer columns. Second, replace collect with sinkparquet so the output is written to disk chunk by chunk and never held in memory.
Exercise
Why is lf.select(pl.len()).collect(engine="streaming") a safe way to check the size of a result before collecting it?
Show answer
It returns a single row containing one number, so the collected result is tiny. The engine still reads the input in chunks, so memory use stays low.