Logical Optimization
Concepts covered: Catalyst Optimizer
With every name resolved, the optimizer rewrites the tree into one that returns the same rows for less work. It works through rules. Each rule looks for a pattern, such as a Filter above an Aggregate, and swaps in an equivalent shape. Rules are grouped into batches, and most batches repeat until a full pass changes nothing or they reach spark.sql.optimizer.maxIterations, 100 by default. No rule reads data: the same tree gets the same rewrite whether the table holds 10 rows or 10 billion.
Rules you will meet in most plans
| Rule | Before | After | What it saves |
|---|---|---|---|
| PushDownPredicates | A Filter above a Project or Aggregate | The Filter moved beneath it | Rows dropped before later steps touch them |
| ColumnPruning | Every column of the table carried upward | Only the columns the query uses | Bytes carried through every step and shuffle |
| ConstantFolding | profit > 10 * 100 | profit > 1000.0 | Arithmetic done once on the driver, not per row |
| CombineFilters | 2 filter calls in a row | 1 Filter joined by AND | 1 operator |
| CollapseProject | 3 chained withColumn calls | 1 Project | 2 operators |
| InferFiltersFromConstraints | status = 'Completed' | isnotnull(status) AND status = 'Completed' | An explicit null test later steps can rely on |
A filter that moves below the groupBy
This program groups first and filters second, the order you might write it after deciding late that only the West matters.
from pyspark.sql import functions as F
orders = spark.table("orders")
by_region = orders.groupBy("region").agg(F.sum("profit").alias("total_profit"))
west = by_region.filter(F.col("region") == "West")
west.explain(extended=True)The optimizer fired 4 rules. EliminateSubqueryAliases removed the SubqueryAlias line, which only recorded the name the table was read under. PushDownPredicates moved the filter beneath the Aggregate, which is legal because the test reads only region, the grouping key: every row that lands in the West group started as a West row, so dropping the rest first cannot change West's total. InferFiltersFromConstraints added isnotnull(region#2). ColumnPruning inserted a Project so order_id and status stop travelling upward. The saving shows up at the shuffle the groupBy needs, which now receives West rows only.
The run below plays that program on 12 orders spread over 3 regions, ending in collect(). Watch each map task drop its East and North rows before computing a partial sum, so the shuffle carries only West sums.
from pyspark.sql import functions as F
by_region = orders.groupBy("region").agg(F.sum("profit").alias("total_profit"))
west = by_region.filter(F.col("region") == "West")
west.collect()| order_id | status | region | profit |
|---|---|---|---|
| 1 | Completed | West | 120 |
| 2 | Completed | East | 80 |
| 3 | Returned | North | -20 |
| 4 | Completed | West | 200 |
| 5 | Pending | East | 45 |
| 6 | Completed | North | 60 |
| 7 | Completed | West | 90 |
| 8 | Returned | West | -15 |
| 9 | Completed | East | 150 |
| 10 | Pending | North | 30 |
| 11 | Completed | West | 75 |
| 12 | Completed | East | 110 |
When a filter has to stay
A filter can move to a lower point only if every row there carries what the test reads. Below an Aggregate, a row has its grouping keys but no totals yet.
- Moves lower in the plan
- region == 'West' after groupBy('region'): it reads a grouping key only
- margin > 5 after withColumn('margin', profit * 0.1): rewritten as profit * 0.1 > 5
- The status test in status == 'Completed' AND total_profit > 0 after groupBy('status')
- Stays where you wrote it
- total_profit > 500 after the agg: the total exists only once the group is complete
- status == 'Completed' OR total_profit > 0: an OR has no half that is safe to move alone
- Any filter on a DataFrame rebuilt from an RDD: Catalyst cannot see into the RDD code
Which filter on summary does the optimizer move below the Aggregate?
from pyspark.sql import functions as F
summary = orders.groupBy("status", "region").agg(
F.sum("profit").alias("total"),
F.count("*").alias("n"),
)- summary.filter(F.col("total") > 1000), because numeric comparisons are cheap to run early
- summary.filter(F.col("n") > 5), because a count can be tallied from each row as it arrives
- summary.filter((F.col("status") == "Completed") | (F.col("total") > 0)), since 1 branch tests a key
- summary.filter(F.col("region") != "Test"), because it reads only a grouping column
The cell groups the practice orders by status and keeps the Completed group. Run it, then move the filter above the groupBy and run again. The row that comes back is identical, and that equality is the whole licence the optimizer needs to make the move on its own.
About this lesson
This section is part of the Catalyst Optimizer: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.