Polars Lazy Query Optimization

Run Polars lazy frames so predicate pushdown, projection pruning, and streaming execution optimize the plan before any data moves.

PythonData Integrity

Code

snippet
import polars as pl

events = pl.DataFrame({
    'user_id': [1, 2, 3, 4, 5, 6],
    'event': ['view', 'click', 'view', 'purchase', 'click', 'view'],
    'amount': [0, 0, 0, 120, 0, 0],
    'day': ['2026-10-21', '2026-10-21', '2026-10-22', '2026-10-22', '2026-10-22', '2026-10-22'],
})

lazy = events.lazy()

report = (
    lazy
    .filter(pl.col('event') != 'view')
    .group_by('day')
    .agg(
        active_users=pl.col('user_id').n_unique(),
        revenue=pl.col('amount').sum(),
        top_event=pl.col('event').mode().first(),
    )
    .sort('day')
    .collect(streaming=True)
)

print(report)

plan = (
    lazy.filter(pl.col('amount') > 0)
    .select(['day', 'amount'])
    .collect_optimized_plan()
)
print('optimized logical plan nodes:', len(str(plan).splitlines()))