Sub topic 6
Reading query plans with EXPLAIN
This chapter assumes you can write SQL joins and aggregations. It also assumes you know that Spark splits a query into stages and tasks, and that a shuffle moves data between executors. Here you learn to read the plan Spark builds for a query, so you can see which work runs in Photon and where the cost is likely to come from.
What a query plan is
Before running a query, Spark turns your SQL or DataFrame code into a tree of operators. An operator is one step, such as scanning a table, filtering rows, joining, or aggregating. EXPLAIN prints that tree without running the query.
The plan goes through several forms:
- Parsed and analyzed logical plan. Table and column names are resolved against the catalog.
- Optimized logical plan. The optimizer rewrites the tree, for example by pushing filters closer to the scan.
- Physical plan. Spark picks concrete operators, such as a broadcast hash join instead of a sort-merge join. This is the plan that runs, and it is the one you read most often.
The EXPLAIN modes
| Mode | What it shows |
|---|---|
| `EXPLAIN` | The physical plan only |
| `EXPLAIN EXTENDED` | Parsed, analyzed, optimized and physical plans |
| `EXPLAIN FORMATTED` | The physical plan as a short outline, followed by a numbered detail block for each operator |
| `EXPLAIN COST` | The optimized logical plan with row-count and size estimates, when statistics exist |
FORMATTED is the easiest to read for real queries, so start there.
EXPLAIN FORMATTED
SELECT c.region, SUM(o.amount) AS total
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
WHERE o.order_date >= '2024-01-01'
GROUP BY c.region;In Python, the equivalent for a DataFrame is df.explain("formatted").
How to read the tree
Read the outline from the bottom up. The leaves at the bottom are scans, and data flows upward through joins and aggregations to the final result at the top. Indentation shows which operators feed which. A join has two children, one for each input.
The numbers in parentheses link the outline to the detail block. Find (4) in the outline, then search for (4) below to see that operator's arguments.
Here is a simplified sketch of the outline for the query above on a Photon cluster. Your output will contain more operators and different numbering.
== Physical Plan ==
AdaptiveSparkPlan (11)
+- == Initial Plan ==
PhotonResultStage (10)
+- PhotonGroupingAgg (9)
+- PhotonShuffleExchangeSource (8)
+- PhotonShuffleMapStage (7)
+- PhotonShuffleExchangeSink (6)
+- PhotonGroupingAgg (5)
+- PhotonProject (4)
+- PhotonBroadcastHashJoin Inner (3)
:- PhotonScan parquet orders (1)
+- PhotonScan parquet customers (2)What to look for
Photon and non-Photon operators
On Photon compute, operators that run in Photon carry a Photon prefix in their names. An operator without the prefix runs in the regular Spark engine. When a Photon operator feeds a non-Photon one, Spark has to convert between the two data formats, and that conversion adds cost. A plan that mixes the two in the middle of the tree deserves a closer look. The next chapters cover why this happens and how to avoid it.
Operator names can change between runtime versions. Check for the Photon prefix as a pattern, not as a fixed list.
Exchange operators
An Exchange (or a Photon shuffle exchange sink and source pair) marks a shuffle. Shuffles write data to disk and send it over the network, so they are usually the most expensive part of a plan. Count them. A plan with one shuffle for the GROUP BY is normal. A plan with several shuffles may be joining or grouping in a way that forces repartitioning again and again.
Scan details
Look at the scan's detail block. Three fields matter most:
- PushedFilters. Filters that the scan applies while reading. If your
WHEREcondition does not appear here, the scan may read more data than needed. - ReadSchema. The columns actually read. Selecting only the columns you need keeps this short.
- PartitionFilters. Filters used to skip whole partitions, if the table is partitioned.
Join type
The join operator tells you the strategy Spark chose. BroadcastHashJoin sends the small side to every executor and avoids shuffling the large side. SortMergeJoin shuffles and sorts both sides. If you expect a small table to be broadcast and you see a sort-merge join, the optimizer probably lacked size information. See the chapter on statistics.
Adaptive plans
When adaptive query execution is on, the top of the plan shows AdaptiveSparkPlan, often with isFinalPlan=false. This means the plan can still change while the query runs. Spark may switch a join strategy or merge small shuffle partitions once it sees real data sizes. EXPLAIN alone shows only the initial plan. To see what actually ran, use the Query Profile or the Spark UI after the query finishes.
Using estimates with EXPLAIN COST
EXPLAIN COST adds Statistics(sizeInBytes=..., rowCount=...) to each logical operator. If a table has no collected statistics, Spark falls back to file sizes and the row counts are missing. Large gaps between these estimates and reality are a common cause of poor join choices. Collect statistics with:
ANALYZE TABLE orders COMPUTE STATISTICS FOR ALL COLUMNS;Then run EXPLAIN COST again and compare. The estimates should now include row counts.
Common mistakes
- Reading top-down. The top shows the last step. Start at the scans to follow the data.
- Assuming the plan is final. With adaptive execution, the printed plan is the starting point.
- Judging by operator count. A long plan with one shuffle can run faster than a short plan with three.
- Ignoring pushed filters. A filter wrapped in a function, such as
WHERE year(order_date) = 2024, often cannot be pushed to the scan the wayorder_date >= '2024-01-01'can. Compare thePushedFiltersfield for both forms. - Assuming
Photonappears everywhere. On clusters or warehouses without Photon, no operator will have the prefix, and that is expected.
Exercise
A plan shows a SortMergeJoin between a very large orders table and a customers table of about 20 MB. Which two things would you check first, and what is one fix?
Show answer
Check whether customers has up-to-date statistics (use EXPLAIN COST to see its estimated sizeInBytes) and whether the plan is adaptive, since the final strategy may differ from the initial plan. If the statistics are missing or stale, run ANALYZE TABLE on customers. If the optimizer still picks a sort-merge join, add a BROADCAST hint on customers so the large table is not shuffled.
Exercise
You run EXPLAIN FORMATTED on a query on Photon compute and see PhotonScan and PhotonGroupingAgg, but the join operator has no Photon prefix. What does that tell you, and where do you look next?
Show answer
The join runs in the regular Spark engine, not in Photon. Data must be converted between engines around it, which adds cost. Look at the join's detail block for the join type and condition, and then check the Query Profile to see how much time the operator takes.