Sub topic 7
A query is a plan: logical plans as trees
This chapter explains what a LazyFrame holds before you call collect(). It assumes you can write Polars expressions (pl.col, select, filter, with_columns, group_by) and that you know how lazy() and collect() behave. By the end you should be able to sketch the tree behind any lazy query.
A LazyFrame holds a plan
A LazyFrame does not hold rows. It holds a description of how to compute them, called a logical plan. Each method you call adds one step to that description and returns a new LazyFrame. No data is touched.
A logical plan is a tree. The tree has two kinds of nodes:
- Leaf nodes are data sources. An in-memory
DataFrameand a file scan such asscan_csvare both leaves. - Inner nodes are operations: filter, projection (
select),with_columns, aggregation, sort, slice, join. Each inner node takes the output of its children as input.
The root of the tree is the final result. Data flows from the leaves up to the root.
import polars as pl
lf = pl.LazyFrame({
"city": ["Oslo", "Lima", "Oslo", "Cairo"],
"temp": [3.0, 19.5, 5.0, 28.0],
})
q1 = lf.filter(pl.col("temp") > 4)
q2 = q1.with_columns(temp_f=pl.col("temp") * 9 / 5 + 32)
q3 = q2.group_by("city").agg(pl.col("temp_f").mean())
print(type(q3))
print(lf.explain(optimized=False))
print(q3.explain(optimized=False))The first print shows LazyFrame. The second shows a plan with only a source node. The third shows an aggregation on top of a with_columns, on top of a filter, on top of the source.
The exact text of explain() output differs between Polars versions. The tree structure does not. Read the text from the bottom up. The innermost, most indented line is the leaf, and the first line is the root.
Plans are immutable and shareable
Calling q1 = lf.filter(...) does not change lf. It creates a new root whose child is the old root. This is why lf.explain(optimized=False) above still shows only the source.
This has two practical consequences:
- You can branch from one
LazyFrameas often as you like.q2and any other query built fromq1both point at the sameq1subtree. - Building a query is cheap. It allocates a few nodes and does no work on the data.
The tree below shows q3, with the root at the bottom to match how explain() prints it.
Joins and unions give the tree more than one branch
A chain of filters and selects looks like a list. A join takes two inputs, so it is a node with two children.
import polars as pl
lf = pl.LazyFrame({
"city": ["Oslo", "Lima", "Oslo", "Cairo"],
"temp": [3.0, 19.5, 5.0, 28.0],
})
countries = pl.LazyFrame({
"city": ["Oslo", "Lima", "Cairo"],
"country": ["NO", "PE", "EG"],
})
warm = lf.filter(pl.col("temp") > 4)
joined = warm.join(countries, on="city", how="left")
print(joined.explain(optimized=False))The printed plan shows a join node with two indented subtrees. One is the filtered lf. The other is the countries source. pl.concat([...], how="vertical") on lazy frames works the same way. It produces a union node with one child per input.
If you reuse one LazyFrame in two places of the same query, for example both sides of a self-join, the shared subtree can appear twice in the printed plan. Common subexpression elimination, covered in a later chapter, can merge repeated work.
Expressions are trees too
The nodes in the plan contain expressions, and expressions have a tree structure of their own. The expression pl.col("temp") * 9 / 5 + 32 is an addition whose children are a division and a literal, and so on down to the column reference.
An expression is data about a computation, not a computation. You can inspect it before any frame exists:
import polars as pl
expr = pl.col("temp") * 9 / 5 + 32
print(expr.meta.root_names())
print(expr.meta.output_name())This prints ['temp'] and then temp. The root names are the input columns the expression reads, and the output name is the name of the resulting column. The optimiser relies on exactly this kind of information. It can see which columns each node reads, so it can reason about what is safe to move or drop.
Every node has a schema
Each node derives its output schema (column names and dtypes) from its children and from its own expressions. A filter keeps its input schema. A with_columns adds or replaces columns. A group_by().agg() replaces the schema with the keys plus the aggregated columns.
Because of this, Polars can answer "what will the result look like?" by walking the tree, without reading any data. It can also catch mistakes early. For example, selecting a column that no earlier node produces is an error. Depending on the Polars version, you see it when you call collect() or earlier, when the schema is first resolved. Do not rely on the error appearing at the moment you write the faulty line.
Logical plan versus physical plan
Polars distinguishes two stages:
| Stage | Describes | Example content | Who changes it |
|---|---|---|---|
| Logical plan | What to compute | Filter, project, join, aggregate | You (by chaining methods) and the optimiser (by rewriting) |
| Physical plan | How to compute it | Which algorithm and execution engine runs each node | Polars, when `collect()` is called |
explain() shows the logical plan. The optimiser rewrites this logical tree into another logical tree that gives the same result at lower cost. Only then is the tree turned into an executable physical plan and run. The next chapter shows how to read the unoptimised and optimised versions side by side.
Why the tree view matters
Thinking in trees makes several behaviours predictable:
- Moving a filter closer to a leaf is a rewrite of the tree. This is the idea behind predicate pushdown.
- Dropping unused columns at the leaf is also a tree rewrite. It is the idea behind projection pushdown.
- A node the optimiser cannot see inside, such as a Python function in
map_elements, limits which rewrites can cross that node. - Order of method calls is the order of nodes in the tree. The optimiser may reorder nodes only when the result is provably the same.
Common mistakes
- Treating a
LazyFrameas if it held data. Printing it shows the plan, not rows. Usecollect()to get aDataFrame. - Expecting a method to modify the frame in place. Methods return a new
LazyFrame, solf.filter(...)on its own line has no lasting effect. - Reading
explain()output top-down as a sequence of steps. Read it bottom-up, from the leaf to the root. - Assuming a column error will surface at the line that caused it. It may appear only at
collect().
Exercise
You build q = lf.filter(pl.col("temp") > 4).select("city") and then call lf.explain(optimized=False). Does the printed plan include the filter and the select? Why or why not? Which node would be the root of q's plan?
Show answer
No. filter and select return new LazyFrames and do not modify lf, so lf's plan still contains only its source. In q's plan the root is the select (projection) node. Its child is the filter node, and the source is the leaf below the filter.
Exercise
A plan contains a join of a filtered orders table with a customers table. How many children does the join node have, and what kind of nodes are the leaves of the whole tree?
Show answer
The join node has two children, one per input. The leaves are the data sources, such as in-memory frames or file scans, with the filter sitting above the orders source.