Sub topic 17
Larger-than-memory queries: streaming and sink_parquet
This chapter assumes you know scan_csv, scan_parquet, filter, group_by and collect() from the earlier chapters. It also assumes you know that a LazyFrame records a plan and that collect() runs it.
The problem with collect()
collect() builds the whole result as one DataFrame in memory. If the result is larger than your RAM, the query fails or the machine starts swapping. The optimiser helps, because pushdown reads less data. But a result that is still large has to go somewhere.
Polars has two answers. Both process the data in batches instead of all at once.
Streaming collect
Pass the streaming engine to collect(). Polars then reads the source in chunks, pushes each chunk through the plan, and combines partial results. The final result still has to fit in memory, so this suits queries that read a lot but return little, such as aggregations.
import polars as pl
pl.DataFrame({
"region": ["EU", "US", "EU", "ASIA"] * 250_000,
"amount": [1.0, -2.0, 3.5, 4.0] * 250_000,
}).write_csv("big.csv")
summary = (
pl.scan_csv("big.csv")
.filter(pl.col("amount") > 0)
.group_by("region")
.agg(pl.col("amount").sum().alias("total"))
.collect(engine="streaming")
)
print(summary.sort("region"))Older Polars versions use collect(streaming=True) for the same purpose. Check which one your installed version supports.
sink_parquet
If the result itself is large, don't collect it. sink_parquet() runs the query and writes batches straight to a file, so a full DataFrame never exists in memory.
import polars as pl
(
pl.scan_csv("big.csv")
.filter(pl.col("amount") > 0)
.sink_parquet("positive.parquet")
)
print(pl.scan_parquet("positive.parquet").select(pl.len()).collect())Unlike collect(), sink_parquet() does not return the data. It runs the query immediately and returns nothing useful. You read the output back with scan_parquet.
Sinks for other formats exist too, such as sink_csv and sink_ndjson. The pattern is the same.
Common errors
- Calling
sink_parqueton a DataFrame. Sinks are LazyFrame methods. Start from ascan_*function or.lazy(). - Expecting every operation to stream. Some operations, such as certain sorts and joins, need to see all the data. Depending on the Polars version, they may fall back to in-memory execution or use more memory than you expect. Test with a realistic file size and watch memory use.
- Collecting a huge result anyway.
collect(engine="streaming")still returns a full DataFrame. Use a sink when the output is large. - Defeating the optimiser. Python UDFs from the previous chapter still block pushdown, so the scan reads more than it needs.
Exercise
You have a 40 GB CSV and want only the rows where status == "ok", saved as Parquet. Your machine has 16 GB of RAM. Which call do you use at the end of the query, and why not collect()?
Show answer
Use pl.scan_csv(...).filter(pl.col("status") == "ok").sink_parquet("ok.parquet"). The filtered result may still be too large for memory, and collect() would build it as one DataFrame. sink_parquet() writes it in batches, so memory use stays bounded.