Sub topic 9
What the optimiser rewrites and why results stay the same
This chapter assumes you know basic Python and the Polars expression API (pl.col, select, filter, with_columns, group_by). It also assumes you have seen that a LazyFrame records a plan and that collect() runs it.
The optimiser rewrites the plan, not the answer
When you call collect(), Polars does not run your steps in the order you wrote them. It first rewrites the logical plan into a cheaper plan that returns the same result. The rewrite is a set of rules. Each rule applies only when it can prove the result will not change.
The rules in this tutorial are:
| Rule | What it does |
|---|---|
| Predicate pushdown | Moves filters toward the data source so fewer rows are read. |
| Projection pushdown | Reads only the columns the query uses. |
| Slice pushdown | Moves `head` and `limit` toward the scan so fewer rows are read. |
| Expression simplification | Rewrites expressions into simpler equivalent forms and fixes types. |
| Common subexpression elimination | Computes a repeated expression once. |
Later chapters cover each rule in detail. Here you learn the shared idea.
Why the result stays the same
Every rule is an equivalence rewrite. Two plans are equivalent if they give the same output for the same input. Filtering rows and then selecting a column gives the same rows as selecting the column and then filtering, provided the filter only needs columns that are still present. The optimiser checks conditions like this before it moves a step.
The example below builds the same query in two forms. The optimiser can reorder the steps in the second form, and both give the same result.
import polars as pl
df = pl.DataFrame({
"city": ["Oslo", "Lima", "Oslo", "Cairo"],
"temp": [3.0, 19.5, 5.0, 28.0],
})
filter_first = df.lazy().filter(pl.col("temp") > 4).select("city")
select_first = df.lazy().select("city", "temp").filter(pl.col("temp") > 4).select("city")
print(filter_first.collect().equals(select_first.collect()))
print(filter_first.explain())
print(select_first.explain())The first print shows True. The two plans printed by explain() should be close to identical, because the optimiser reduces both to one shape.
Seeing the rewrite
You can compare the plan as written with the plan after rewriting. explain(optimized=False) shows your plan unchanged, and explain() shows the optimised plan.
import polars as pl
lf = (
pl.LazyFrame({"a": [1, 2, 3, 4], "b": [10, 20, 30, 40]})
.select("a", "b")
.filter(pl.col("a") > 2)
.select("b")
)
print(lf.explain(optimized=False))
print(lf.explain())Common errors
- Assuming the written order is the run order. Polars may run a filter before a step you wrote earlier. Do not rely on side effects from the order of steps.
- Expecting every query to be optimised. A rule is skipped when it cannot prove safety. Python functions inside
map_elementsare one case, covered in a later chapter. - Judging a plan by the unoptimised output. Read
explain()without arguments to see what will run.
Exercise
Why can Polars move a filter earlier in a plan without changing the result, and what must be true for that move to be allowed?
Show answer
The move is an equivalence rewrite: filtering earlier gives the same rows as filtering later. It is allowed only when the filter's columns are available at the earlier point and no step in between, such as an opaque Python function, makes the change unsafe.