Sub topic 4
Reading the query plan
This chapter assumes you can write basic Polars expressions and have seen scan_parquet and scan_csv. Here you will learn to print a lazy query's plan, read it, and use it to check that Polars reads only the data you need. That check matters before you run anything on a file larger than memory.
What a query plan is
A LazyFrame does not hold data. It holds a description of the work you asked for, called the logical plan. Each call such as filter, select, or group_by adds a node to that plan. Nothing runs until you call collect, sink_parquet, or a similar method.
Before execution, Polars rewrites the plan with an optimizer. The optimizer removes redundant work and moves operations closer to the data source. Two of its most useful rewrites are:
- Projection pushdown: only the columns the query needs are read from the file.
- Predicate pushdown: filter conditions are handed to the scan, so rows that fail the filter are dropped as early as possible.
The streaming engine runs the optimized plan, not the code as you wrote it. So the plan is the best place to see what will happen to your memory.
Printing the plan with explain
LazyFrame.explain() returns the optimized plan as text. Pass optimized=False to see the plan as you wrote it. The script below creates a small Parquet dataset in a temporary directory, so you can run it as is.
import tempfile
from pathlib import Path
import polars as pl
root = Path(tempfile.mkdtemp())
(root / "events").mkdir()
for i in range(3):
pl.DataFrame(
{
"user_id": [1, 2, 3, 4],
"status": ["ok", "fail", "ok", "ok"],
"amount": [10.0, 5.0, 7.5, 3.0],
"country": ["DE", "US", "FR", "US"],
"note": ["a", "b", "c", "d"],
}
).write_parquet(root / "events" / f"part-{i}.parquet")
lf = (
pl.scan_parquet(str(root / "events" / "*.parquet"))
.filter(pl.col("status") == "ok")
.select("user_id", "amount")
)
print("--- as written ---")
print(lf.explain(optimized=False))
print("--- optimized ---")
print(lf.explain())The exact wording and layout of the output change between Polars versions. The output looks roughly like this:
--- as written ---
SELECT [col("user_id"), col("amount")] FROM
FILTER [(col("status")) == ("ok")] FROM
Parquet SCAN [.../part-0.parquet, ... 2 other sources]
PROJECT */5 COLUMNS
--- optimized ---
simple π 2/2 ["user_id", "amount"]
Parquet SCAN [.../part-0.parquet, ... 2 other sources]
PROJECT 2/5 COLUMNS
SELECTION: [(col("status")) == ("ok")]Do not match this text character by character. Learn the vocabulary instead.
How to read it
Read the plan from the inside out. The scan is the innermost node, with the deepest indentation, and it runs first. Each node above it takes the output of the node below. The node at the top is the last step and produces the result.
| Plan text | Meaning |
|---|---|
| `Parquet SCAN` or `CSV SCAN` | The data source. The listed paths show which files will be read. |
| `PROJECT */5 COLUMNS` | The scan reads all 5 columns. |
| `PROJECT 2/5 COLUMNS` | Projection pushdown worked. Only 2 of 5 columns are read. |
| `SELECTION: [...]` | A predicate attached to the scan. Filtering happens while reading. |
| `FILTER ... FROM` | A separate filter node above the scan. It runs after the data is read. |
| `AGGREGATE` | A `group_by` with aggregations. |
| `SORT BY`, `JOIN` | Operations that often need to see much of the data at once. |
The key comparison is between the two printouts. In the "as written" plan, the filter sits in its own node and the scan reads every column. In the optimized plan, the filter has become a SELECTION on the scan and the projection shows 2/5 COLUMNS. Polars changed your plan so that it reads less data.
Why this matters for memory
Pushdown is the cheapest memory saving available, because it happens before the streaming engine processes any chunks.
- Parquet stores data by column. When the plan says
2/5 COLUMNS, the other three columns are never decoded. A wide table with a few long text columns can shrink a lot this way. - Parquet files also keep min and max statistics per row group. A predicate on the scan lets Polars skip row groups whose statistics rule out any match.
- For CSV, projection pushdown still saves memory because unneeded columns are not kept. Polars must still parse every line, though, so you save less time than with Parquet.
If the plan shows PROJECT */N COLUMNS for a query that uses only a few columns, something prevented pushdown. Find out what before you run the query on a large file.
When pushdown does not happen
Predicate pushdown is only safe when moving the filter does not change the result. The optimizer is conservative, so these patterns are common reasons to see a separate FILTER node far above the scan.
Compare these two filters on the same aggregation:
import tempfile
from pathlib import Path
import polars as pl
root = Path(tempfile.mkdtemp())
pl.DataFrame(
{
"user_id": [1, 1, 2, 3, 3, 4],
"amount": [10.0, 5.0, 7.5, 3.0, 9.0, 12.0],
}
).write_parquet(root / "events.parquet")
agg = (
pl.scan_parquet(str(root / "events.parquet"))
.group_by("user_id")
.agg(pl.col("amount").sum().alias("total_amount"))
)
# Filter on the grouping key: can run before the aggregation.
by_key = agg.filter(pl.col("user_id") > 2)
# Filter on an aggregated value: only exists after the aggregation.
by_total = agg.filter(pl.col("total_amount") > 10)
print("--- filter on key ---")
print(by_key.explain())
print("--- filter on total ---")
print(by_total.explain())In the first plan, the condition on user_id can move to the scan, because removing whole groups before aggregating gives the same answer. In the second plan, total_amount does not exist until the aggregation has run. The filter must stay above the AGGREGATE node, so the scan still reads every row.
Other things that commonly block pushdown:
- Filtering on a column produced by a window expression, a
shift, or acum_*function. These depend on neighboring rows. - Opaque Python code such as
map_elementsormap_batches. The optimizer cannot see inside it, so it may not move conditions past it or prune columns around it. - Filters applied after a
joinon columns that come from the nullable side of an outer join.
When you hit one of these, restructure the query so the filter touches only source columns and comes first. For the aggregation example, you can filter on a source column before grouping instead of on the total afterwards. This is correct only when it means what you want. Filtering amount before summing is a different question from filtering the sum.
Viewing the plan as a graph
For long queries, a picture is easier than text. lf.show_graph() renders the plan as a diagram. It needs the Graphviz program installed on your machine. To work without it, pass raw_output=True to get the graph source as a string, or just use explain().
import polars as pl
lf = pl.LazyFrame({"a": [1, 2, 3], "b": [4, 5, 6]}).filter(pl.col("a") > 1)
dot = lf.show_graph(raw_output=True)
print(dot[:60])A checklist before running on big data
Run explain() on your real query, with the real file paths, and check each point.
- The
SCANnode lists the files you expect, not more. - The projection shows only the columns you use, such as
3/40 COLUMNS. - Filters on source columns appear as
SELECTIONon the scan. - You know which nodes are
AGGREGATE,SORT, orJOIN. These are the places where memory use can grow, and a later chapter covers them. - No node you did not write has appeared, such as a stray extra column that forces a wider projection.
Common mistakes
- Reading the plan from the top and expecting that to be the first step. The innermost node runs first.
- Calling
explain()on aDataFrame. It exists only onLazyFrame. Usedf.lazy().explain()if you must, but a plan built from an in-memory frame has no file scan to inspect. - Judging pushdown from your code. You may write the filter last, but the optimizer can still move it. Judge from the printed plan.
- Selecting columns with a broad expression.
pl.all()or a regular expression that matches many columns keeps those columns in the projection. Name the columns you need.
Exercise
You run explain() on a query over a Parquet file with 30 columns. The plan shows PROJECT 30/30 COLUMNS and a separate FILTER node above the scan. Your code selects 3 columns and filters on a column named status. Name two possible causes, and describe one change you would make to the query.
Show answer
Possible causes: the select happens after something the optimizer cannot see through, such as map_elements or map_batches. Or the filter depends on a column built by a window or cumulative expression instead of a source column. Another cause is a broad selector such as pl.all() keeping every column in the projection. A fix is to select the 3 needed columns by name and apply the filter on the source column status directly after the scan, before any custom Python code. Then run explain() again and check that the projection reads 3/30 COLUMNS and the filter appears as SELECTION on the scan.
Exercise
In the plan for scan.group_by("user_id").agg(pl.col("amount").sum().alias("total_amount")), why can a filter on user_id > 2 move to the scan but a filter on total_amount > 10 cannot?
Show answer
user_id is the grouping key and exists in the source data, so dropping rows with user_id <= 2 before aggregating gives the same result as dropping those groups afterwards. total_amount is created by the aggregation, so it does not exist at the scan. That filter has to stay above the AGGREGATE node, and the scan must still read all rows.