Sub topic 8
Reading explain() output, before and after optimisation
This chapter assumes you can write Polars expressions and know that a LazyFrame records a query without running it. You should also know that collect() runs it. Here you will learn to read the text that explain() prints and to spot what the optimiser changed.
What explain() returns
LazyFrame.explain() returns a string that describes the logical plan of a query. It does not read any data or run the query. By default it shows the optimised plan, which is what collect() would actually execute. With optimized=False it shows the plan exactly as you wrote it.
Comparing the two is the most direct way to see the optimiser at work.
A query to inspect
The following script writes a small CSV file, then builds a lazy query on it.
import polars as pl
pl.DataFrame({
"id": [1, 2, 3, 4],
"region": ["EU", "US", "EU", "EU"],
"product": ["pen", "pen", "ink", "ink"],
"amount": [10.0, 5.0, 7.5, 2.5],
}).write_csv("sales.csv")
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
print(lf.collect())The file has four columns, but the query only uses region, product and amount. The column id is never needed.
Reading the plan
A plan is a tree, printed as indented text. Each line is an operation. The data source is at the bottom, and each operation above it consumes the output of the one below. So read from the bottom up: the bottom line runs first, and the top line produces the final result.
The FROM lines you see between operations are separators. They mean "the input of the operation above comes from the operation below".
Here is the unoptimised plan. The exact wording differs between Polars versions, so treat this as a representative shape and not as text to match.
AGGREGATE[maintain_order: false]
[col("amount").sum().alias("total")] BY [col("product")]
FROM
FILTER [(col("region")) == ("EU")]
FROM
Csv SCAN [sales.csv]
PROJECT */4 COLUMNSReading from the bottom:
- Scan
sales.csvand keep all four columns.*/4means "every column out of four". - Filter the rows to
region == "EU". - Group by
productand sumamountintototal.
This matches your code line by line. Nothing has been rewritten yet.
Now the optimised plan:
AGGREGATE[maintain_order: false]
[col("amount").sum().alias("total")] BY [col("product")]
FROM
Csv SCAN [sales.csv]
PROJECT 3/4 COLUMNS
SELECTION: [(col("region")) == ("EU")]Two things changed.
- The separate
FILTERnode is gone. Its condition now appears asSELECTIONinside the scan node. This is predicate pushdown: the reader applies the filter while loading, so rejected rows never become part of a DataFrame. PROJECT */4 COLUMNSbecamePROJECT 3/4 COLUMNS. This is projection pushdown: the optimiser worked out that only three columns are needed anywhere in the query, and told the scan to skipid.
The result of collect() is identical either way. The optimiser only changes how much work is done.
Vocabulary of plan nodes
Node names vary by version, but these appear in most outputs.
| Text in the plan | Meaning |
|---|---|
| `Csv SCAN [path]`, `PARQUET SCAN [path]` | Read from a file. A scan node can carry a projection and a selection. |
| `DF [...]` | An in-memory DataFrame used as the source. |
| `PROJECT n/m COLUMNS` | The scan keeps `n` of `m` columns. `*` means all. |
| `SELECTION: [...]` | A predicate applied inside the scan. |
| `FILTER [...] FROM` | A separate filter node that runs after its input is produced. |
| `SELECT [...] FROM` | A column selection or computation. |
| `WITH_COLUMNS [...]` | New or replaced columns. |
| `AGGREGATE ... BY [...]` | A `group_by` with its aggregations. |
A SELECTION inside a scan and a FILTER above it mean different things. The first reduces what gets read. The second runs on data that was already loaded. If you expected a pushdown and still see a FILTER node, the optimiser could not push it down.
How the shape of the tree shows the optimisation
The diagram shows the same query before and after.
The optimised tree is shorter, and the scan node carries more information. When you read an optimised plan, look at the scan node first. It tells you which columns and which rows the reader was asked for.
When the plan looks the same
Sometimes the optimised plan matches the unoptimised one. This is not a bug. It usually means one of these:
- The query has nothing to optimise, for example a plain
selectof every column. - Something blocks the optimiser, such as a Python function. A later chapter covers these barriers.
- The source cannot accept the pushdown. For an in-memory
LazyFrame, a filter can still move toward the source, but there is no file reader to save work.
Do not rely on one specific line of text. Check for the change you expect: a lower n in PROJECT n/m, or a predicate inside the scan.
A workflow for checking a query
- Print
lf.explain(optimized=False)and confirm it matches what you meant to write. - Print
lf.explain()and read it bottom-up. - Look at the scan node: are the columns reduced and is your predicate present?
- Look for stray
FILTERorSELECTnodes sitting above the scan that you expected to move down. - Only then time
collect(). A plan that looks right is a better starting point than a stopwatch.
Common mistakes
- Reading the plan top-down. The first operation to run is at the bottom.
- Expecting the unoptimised plan to be what runs.
collect()uses the optimised one by default. - Treating
PROJECT */4 COLUMNSas an error. It only says that no column pruning has happened at that stage. - Comparing plans from different Polars versions and concluding that the optimiser regressed. The wording changes often.
Exercise
You print lf.explain(optimized=False) and lf.explain() for a query on a 10-column Parquet file. The first plan has a FILTER node above PARQUET SCAN with PROJECT */10 COLUMNS. The second has no FILTER node, and the scan shows PROJECT 2/10 COLUMNS and a SELECTION. Which two optimisations were applied, and does the result of collect() change?
Show answer
Predicate pushdown moved the filter into the scan as the SELECTION, and projection pushdown reduced the scan to the 2 columns the query needs. The result of collect() does not change. Only the amount of data read and processed does.