Sub topic 3
Projection Pushdown: Read Only the Columns You Use
Assume basic Python, Polars DataFrames, Polars expressions, and CSV or Parquet files. This chapter focuses on how the lazy optimiser reduces work before execution.
Projection pushdown: read only the columns you use
Projection pushdown moves a select operation toward the file scan. If a Parquet file has 40 columns but your query uses three, Polars asks the scan to read only those three columns.
import polars as pl
query = (
pl.scan_parquet("events.parquet")
.select("user_id", "country", "timestamp")
.filter(pl.col("country") == "NO")
)
print(query.explain())
result = query.collect()This reduces disk reads and memory use. It works best when the source supports column selection, especially Parquet.
Slice pushdown
A slice is a row limit, such as head(5) or limit(5). Slice pushdown moves that limit toward the scan when safe, so Polars can avoid reading unnecessary rows.
Expression simplification and type coercion
Polars can simplify expressions before execution. For example, a filter containing x > 0 and x > 10 can discard the weaker condition. Type coercion converts compatible values to a common type so comparisons and arithmetic are well-defined.
Common subexpressions and `collect_all`
Common subexpression elimination computes a repeated expression once and reuses it. collect_all can also run several lazy queries together and reuse shared scan work.
base = pl.scan_csv("sales.csv").filter(pl.col("amount") > 0)
by_region = base.group_by("region").agg(pl.col("amount").sum())
by_product = base.group_by("product").agg(pl.col("amount").mean())
region_result, product_result = pl.collect_all([by_region, by_product])What blocks the optimiser
A Python UDF, or user-defined function, is code Polars usually cannot inspect. For example, map_elements can hide column dependencies and prevent pushdown. Prefer native expressions such as pl.col("x") * 2.
Compare plans and handle large results
Use explain(optimized=False) to inspect the written plan. Use explain() to inspect the rewritten plan. Differences reveal which optimisations occurred.
For data larger than memory, collect with streaming or write directly with sink_parquet:
query.collect(engine="streaming")
query.sink_parquet("filtered-events.parquet")Exercise
Which operation asks Polars to write a lazy result directly to Parquet?
Show answer
sink_parquet("file.parquet").