Sub topic 12
Slice pushdown: head and limit reach the scan
This chapter assumes you know how to build a LazyFrame with scan_csv or scan_parquet, how explain() prints a plan, and the idea of predicate and projection pushdown from earlier chapters. Here we look at the third pushdown, which applies to head, limit, and slice.
What slice pushdown does
A slice keeps a fixed range of rows. head(n) and limit(n) keep the first n rows. slice(offset, length) keeps length rows starting at offset.
If you write scan_csv("big.csv").head(5), the unoptimised plan says "read the whole file, then keep five rows". Reading a million rows to throw away all but five is wasteful. Slice pushdown moves the slice towards the data source, so the scan itself stops after it has produced enough rows.
The result does not change. Only the amount of work does.
Seeing it in a plan
The example below writes a small CSV to a temporary directory, so you can run it as is. It compares the plan as written, the optimised plan, and a plan with slice pushdown switched off.
import tempfile
from pathlib import Path
import polars as pl
with tempfile.TemporaryDirectory() as d:
path = Path(d) / "numbers.csv"
pl.DataFrame(
{
"id": list(range(1_000)),
"value": [i * 0.5 for i in range(1_000)],
}
).write_csv(path)
lf = (
pl.scan_csv(path)
.with_columns(double=pl.col("value") * 2)
.head(3)
)
print(lf.explain(optimized=False))
print("-----")
print(lf.explain())
print("-----")
print(lf.explain(slice_pushdown=False))
print("-----")
print(lf.collect())In the unoptimised plan, the slice node is at the top of the tree and the scan is at the bottom. In the optimised plan, the scan node carries the row limit itself. The exact label depends on your Polars version, so look for an N_ROWS or SLICE annotation in the scan node. In the third plan, with slice pushdown disabled, the slice stays at the top.
The slice_pushdown=False keyword is accepted by explain() and collect(). In recent releases the same switch is also available through a QueryOptFlags object. If your version warns that the keyword is deprecated, use that object instead.
How the slice travels down the tree
The optimiser moves the slice down one node at a time. At each node it asks whether the rows that survive the slice would be the same if the slice ran earlier.
For some nodes the answer is yes, so the slice moves past them:
selectandwith_columnswith element-wise expressions. Each output row depends only on the same input row.- Renames and column reordering.
- Scans of CSV and Parquet, where the slice is absorbed into the reader.
For other nodes the answer is no, so the slice stays above them:
filter. Which rows survive depends on the data, so the first five input rows are not the first five output rows.sort. The first rows after sorting can come from anywhere in the input.group_by,unique, and most joins. Their output rows are derived from many input rows.
The diagram below shows both cases.
A slice after a filter
Here the slice is placed after a filter.
import tempfile
from pathlib import Path
import polars as pl
with tempfile.TemporaryDirectory() as d:
path = Path(d) / "numbers.csv"
pl.DataFrame(
{"id": list(range(1_000)), "value": [i * 0.5 for i in range(1_000)]}
).write_csv(path)
lf = pl.scan_csv(path).filter(pl.col("value") > 100).head(3)
print(lf.explain())
print(lf.collect())The filter is pushed into the scan as a predicate, as you saw in the predicate pushdown chapter. The slice cannot move above the filter, because the scan must find rows with value > 100 before it can count three of them. Whether the reader can stop early once it has found three matching rows depends on the Polars version and the file format. Read the optimised plan instead of assuming.
The practical rule is that a slice placed directly on the scan, or separated from it only by element-wise steps, is cheap. A slice placed after a filter, sort, or aggregation is still correct, but it saves less reading.
Where the slice goes matters
These two queries ask for different things.
import polars as pl
lf = pl.LazyFrame({"x": [5, 1, 4, 2, 3]})
first_then_sort = lf.head(3).sort("x")
sort_then_first = lf.sort("x").head(3)
print(first_then_sort.collect()["x"].to_list())
print(sort_then_first.collect()["x"].to_list())The first query takes the first three rows and sorts them, giving [1, 4, 5]. The second sorts everything and takes the three smallest values, giving [1, 2, 3]. The optimiser never swaps these, because that would change the answer. For the second form, Polars may combine sort and head into one operation that only tracks the top rows instead of fully sorting. Check the plan if the sort is the expensive part of your query.
Gotchas
- Row order must mean something.
headis only predictable if the input order is. A CSV or Parquet file has a file order. The output ofgroup_bydoes not have a guaranteed order unless you passmaintain_order=Trueor sort afterwards. A slice after an unordered step may return different rows between runs. - Several files. With a glob such as
scan_parquet("data/*.parquet"), a slice can stop the scan after the first files supply enough rows. Which file counts as first follows the order in which Polars expands the paths, so do not rely on it unless you have checked it. tailis different. Taking the last rows needs the end of the data. For many formats the reader cannot jump to the end, sotailoften saves less thanhead.- Opaque steps. If a Python function in
map_elementssits between the slice and the scan, the optimiser cannot be sure the step is element-wise and may leave the slice above it. The UDF then runs on every row. Replace it with native expressions when you can. headon a LazyFrame is not a preview. It is part of the query, and the whole plan still runs oncollect(). A cheap preview comes from puttingheadearly, next to the scan.
Checking that it worked
When a query seems slow despite a head, follow this routine:
- Print
lf.explain()and look at the scan node for a row limit. - If the scan has no limit, read the nodes between the slice and the scan. Look for a filter, sort, group, join, or UDF.
- Compare with
lf.explain(slice_pushdown=False)to confirm that the optimiser did something. - Move the slice earlier if the logic allows it, or replace the blocking step.
Exercise
You run pl.scan_parquet("events.parquet").sort("ts").head(10).collect(). Does the Parquet reader stop after 10 rows? Explain. Then give a query shape where it would.
Show answer
No. The reader cannot stop early, because the ten smallest ts values can be anywhere in the file, so the sort needs every row. The slice stays above the sort. Polars may merge sort and head into a cheaper top-k operation, but the scan still reads all the rows. A shape where the slice reaches the scan is pl.scan_parquet("events.parquet").select("user_id", "ts").head(10), because select of plain columns is element-wise and the scan only needs the first 10 rows.
Exercise
A colleague writes lf.with_columns(y=pl.col("x").map_elements(lambda v: v + 1, return_dtype=pl.Int64)).head(5) on a large CSV scan. What would you check in explain(), and what would you change?
Show answer
Check whether the scan node shows a row limit. If it does not, the Python function is likely keeping the slice above the with_columns step, so the function runs over all the rows. Change the step to the native expression pl.col("x") + 1, or move head(5) directly after scan_csv. Then run explain() again to confirm that the scan carries the limit.