Sub topic 17
Reading query plans, shuffles and caching
This chapter assumes you can build DataFrames, chain transformations, and run actions in a Databricks notebook. It also assumes you know how groupBy and join work. Here you will learn to read a query plan, spot the shuffles that make cells slow, and use caching when it helps.
Why a plan matters
Spark does not run a transformation when you write it. It records the steps and builds a plan. An action such as count() or show() then runs that plan. The explain() method prints the physical plan, which is the version Spark will execute.
from pyspark.sql import functions as F
orders = spark.createDataFrame(
[
(1, "alice", "2024-01-05", 120.0),
(2, "bob", "2024-01-06", 75.5),
(3, "alice", "2024-02-10", 30.0),
(4, "carol", "2024-02-11", None),
],
"order_id INT, customer STRING, order_date STRING, amount DOUBLE",
)
customers = spark.createDataFrame(
[("alice", "US"), ("bob", "DE")],
"customer STRING, country STRING",
)
joined = orders.join(customers, on="customer", how="left")
joined.explain()Read the plan from the bottom up. The bottom nodes are scans of the data. Nodes above them filter, project, join or aggregate the rows. The top node produces the final result.
Shuffles
A shuffle is the movement of rows between machines so that rows with the same key end up together. In a plan, a shuffle appears as an Exchange node. Joins on large tables and groupBy aggregations usually need one.
Shuffles are costly because they write data to disk, send it across the network, and wait for the slowest task. When a cell is slow, look for Exchange nodes first.
Some shuffles can be avoided or reduced:
- Filter and select columns before a join, so fewer rows move.
- Do not call
orderByordistinctunless you need them. Both can trigger a shuffle. - Spark may broadcast a small table to every worker instead of shuffling both sides. The plan then shows
BroadcastHashJoinrather thanSortMergeJoin. Adaptive query execution (AQE) can switch to a broadcast at run time.
Caching
If you use one DataFrame in several actions, Spark recomputes it each time. cache() keeps the result in memory, and on disk if it does not fit, after the first action fills it.
joined.cache()
joined.count() # an action that fills the cache
joined.show() # reads from the cachecache() is lazy too. Nothing is stored until an action runs. When you are done, release the memory with joined.unpersist().
Common errors
- Calling
cache()and expecting it to run. With no action, nothing is cached. - Reading the plan top down. Start at the bottom to follow the order of execution.
- Caching early in a pipeline, before filters that would have made the data smaller.
- Comparing timings from a first run and a later run without noting the cache.
Exercise
You run joined.cache() and then joined.show(). A teammate says the data is now fully cached. Is that right, and what would you run to be sure the cache is filled?
Show answer
Not necessarily. cache() is lazy, and show() usually reads only enough rows to display 20, so it may fill only part of the cache. Run a full action such as joined.count() to materialize all of it.
Exercise
In the output of explain(), which node name tells you a shuffle happens, and where in the plan do you start reading?
Show answer
The Exchange node marks a shuffle. Start reading at the bottom of the plan, where the data is scanned, and move up toward the final result.