Sub topic 8
Reading explain() output, before and after optimisation
This chapter assumes you know the Polars expression API (pl.col, filter, select, group_by) and have built a LazyFrame before. Here you learn to read the plan that explain() prints, and to compare the plan as you wrote it with the plan Polars will actually run.
What explain() shows
A LazyFrame does not hold data. It holds a logical plan, which is a tree of steps. explain() returns that tree as text, so you can see it without running the query.
import polars as pl
lf = (
pl.scan_csv("sales.csv")
.filter(pl.col("region") == "EU")
.group_by("product")
.agg(pl.col("amount").sum().alias("total"))
)
print(lf.explain(optimized=False)) # the plan as you wrote it
print(lf.explain()) # the plan after optimisation
df = lf.collect()Two calls give two views:
explain(optimized=False)prints the plan in the order you wrote the steps.explain()prints the plan after the optimiser has rewritten it. This is the plancollect()runs.
Reading the tree
Read the plan from the bottom up. The bottom node is the data source. Each node above it takes the output of the node below and transforms it. The top node is the final result.
For the query above, the unoptimised plan has roughly this shape:
AGGREGATE
[col("amount").sum().alias("total")] BY [col("product")]
FROM
FILTER [(col("region")) == ("EU")]
FROM
Csv SCAN [sales.csv]
PROJECT */3 COLUMNSThe exact wording varies between Polars versions, so focus on the structure. The scan reads every column (PROJECT */3 COLUMNS). The filter sits above the scan and runs after the file is read.
Before and after
The optimised plan moves work toward the scan. You should see two changes:
- The filter becomes a predicate on the scan node, often shown as
SELECTION. Rows that fail the test are dropped while reading. - The
PROJECTline lists only the columns the query needs, hereregion,productandamount.
The result is the same. The plan is only cheaper.
A second example
A plan that reads only a few columns and a few rows makes the effect easy to spot.
import polars as pl
lf = (
pl.scan_parquet("events.parquet")
.select("user_id", "ts", "country")
.filter(pl.col("country") == "NO")
.head(5)
)
print(lf.explain())
print(lf.collect())In the optimised output, check three things: the scan lists only user_id, ts and country, the country test appears inside the scan, and the row limit is attached to the scan too.
Common mistakes
- Reading the plan top-down. Execution starts at the bottom.
- Expecting identical text in every version. Compare structure, not exact strings.
- Calling
explain()and assuming it ran the query. It does not read any data.
Exercise
In an optimised plan, the scan node lists 3 columns and the filter appears as a selection on the scan. Which two optimisations produced this?
Show answer
Projection pushdown limited the scan to the needed columns, and predicate pushdown moved the filter into the scan.