Sub topic 15
Reading query plans and optimizations
This chapter assumes you can write filter, group_by and agg expressions, and that you know the difference between a DataFrame and a LazyFrame. Here you will learn to read the plan Polars prints and to recognize the two optimizations you will see most often.
What a query plan is
A lazy query does not run when you write it. Polars records each step as a tree of operations. This tree is the query plan. Before running it, Polars rewrites the tree into a cheaper one that returns the same result. explain() prints the plan so you can inspect it.
Print a plan
This script writes a small file so the example runs as shown.
import polars as pl
pl.DataFrame(
{
"region": ["north", "south", "north", "east"],
"amount": [10, -5, 30, 20],
"note": ["a", "b", "c", "d"],
}
).write_csv("sales.csv")
lazy_result = (
pl.scan_csv("sales.csv")
.filter(pl.col("amount") > 0)
.group_by("region")
.agg(pl.col("amount").sum().alias("total"))
)
print(lazy_result.explain(optimized=False))
print(lazy_result.explain())
print(lazy_result.collect())explain(optimized=False) shows the plan as you wrote it. explain() shows the plan after optimization. The exact text differs between Polars versions, but the optimized plan looks roughly like this:
AGGREGATE
[col("amount").sum().alias("total")] BY [col("region")]
FROM
Csv SCAN [sales.csv]
PROJECT 2/3 COLUMNS
SELECTION: [(col("amount")) > (0)]Read the plan from the bottom up
The data source is at the bottom. Each line above it works on the output of the line below. Here the order is:
- Scan
sales.csv. - Keep only the columns the query needs.
- Apply the filter while reading.
- Aggregate by
region.
The unoptimized plan instead shows a FILTER step sitting above a scan that reads every column. The optimizer moved the filter into the scan.
The two optimizations to look for
| Optimization | Plan text | Effect |
|---|---|---|
| Projection pushdown | `PROJECT 2/3 COLUMNS` | The scan reads only columns the query uses. The `note` column is never loaded. |
| Predicate pushdown | `SELECTION: [...]` | Rows that fail the filter are dropped during the read, so they never reach later steps. |
Polars also does other rewrites, such as combining repeated sub-expressions and simplifying constant expressions. The plan text names them when they apply.
Common reasons pushdown does not happen
- Python UDFs. Polars cannot see inside
map_elements. It must assume the function needs every column, so projection pushdown is often lost. - Eager reading.
pl.read_csvloads the whole file before any later filter runs. Usepl.scan_csvto give the optimizer a chance. - Reading the plan as a script. The order in the plan is not the order you wrote. The result is the same, but the work is arranged differently.
Exercise
You run explain() on a lazy query that starts with pl.scan_csv("sales.csv") and filters on amount. The scan line says PROJECT */3 COLUMNS and has no SELECTION. Name one likely cause and one change to try.
Show answer
A Python UDF, such as map_elements in the query, hides which columns and rows are needed, so Polars cannot push the projection or the filter into the scan. Replace the UDF with native expressions, then run explain() again and check that PROJECT shows fewer columns and SELECTION appears.