Sub topic 2
Predicate and Projection Pushdown
Assume basic Python, DataFrame operations, and Polars expressions such as filter, select, and group_by. Predicate pushdown moves filters closer to the file scan. Projection pushdown selects only the needed columns at the scan. Both reduce the data read and carried through the query.
import polars as pl
lf = (
pl.scan_parquet("events/*.parquet")
.filter(pl.col("status") == "ok") # predicate pushdown
.select("user_id", "amount") # projection pushdown
)
print(lf.explain())For Parquet, Polars can often skip row groups that cannot contain matching values and read only the selected columns. CSV has fewer opportunities for skipping data because it is a row-oriented text format.
How the streaming engine processes data in chunks
A lazy query describes work without executing it immediately. When the query runs with the streaming engine, Polars reads input in chunks called morsels. It applies supported operations to each chunk and passes partial results through the plan.
Streaming reduces peak memory, but it does not make every operation constant-memory. A group_by may keep one accumulator per group. A join may need to keep a hash table. A sort may need to retain much of its input.
Running a query with the streaming engine
Call collect(engine="streaming") when the result fits in memory but the input does not:
result = (
pl.scan_parquet("events/*.parquet")
.filter(pl.col("status") == "ok")
.group_by("user_id")
.agg(pl.col("amount").sum().alias("total_amount"))
.collect(engine="streaming")
)Inspect explain() to verify that filters and column selection appear near the scan. The exact plan text depends on the Polars version.
Sinking results straight to disk
If the result is also too large to collect, use a sink. A sink executes the lazy query and writes output incrementally.
(
pl.scan_csv("events.csv")
.filter(pl.col("amount") > 0)
.with_columns(
(pl.col("amount") * 100)
.cast(pl.Int64)
.alias("amount_cents")
)
.sink_parquet("events_clean.parquet")
)Partitioned Parquet is often a good layout for repeated filtering because related files can be skipped before processing.
Exercise
Which two pushdown optimizations reduce data read from a Parquet scan?
Show answer
Predicate pushdown applies filters near the scan, and projection pushdown reads only the required columns.