Sub topic 5
Transformations, actions and lazy evaluation
This chapter assumes you can run a cell in a Databricks notebook, you know that spark is already defined, and you have built a small DataFrame like the orders example from the earlier chapters. It explains why some lines of code finish instantly while others start a job, and how to reason about that.
The working model
Every DataFrame method falls into one of two groups.
- A transformation describes a new DataFrame from an existing one. Examples are
select,filter,withColumn,groupBy(...).agg(...),join, andorderBy. A transformation does not read or compute any data. It returns a new DataFrame immediately. - An action asks for a result. Examples are
show,count,collect,take,first,toPandas,display, and any write such assaveAsTable. An action makes Spark plan the work and run a job on the cluster.
Spark is lazy. It records the transformations as a plan, and it runs that plan only when an action needs the result. A DataFrame is therefore a recipe plus a schema. It is not a container of rows held in memory.
The code below uses the orders DataFrame from the earlier chapter. It has four rows, one of which has a null amount.
from pyspark.sql import functions as F
big_orders = (
orders
.filter(F.col("amount") > 50)
.select("order_id", "customer", "amount")
.withColumn("amount_rounded", F.round("amount"))
)
big_orders.show()The assignment to big_orders returns at once, no matter how large orders is. No job runs until show() is called. If you run only the first statement, the Spark UI shows no new job for that cell.
Why Spark is lazy
Laziness lets Spark see the whole chain before it does any work. The optimizer, called Catalyst, can then rewrite the plan:
- It can push a filter as close to the data source as possible, so less data is read.
- It can read only the columns that the query uses.
- It can combine adjacent steps, such as a filter and a projection, into one pass over the data.
- It can choose a join strategy based on table sizes.
If Spark ran each line as soon as you wrote it, none of these rewrites would be possible. The order in which you write transformations is therefore not always the order in which Spark runs them.
Narrow and wide transformations
Not all transformations cost the same. The difference matters later when you read query plans.
| Kind | What it does | Examples | Data movement |
|---|---|---|---|
| Narrow | Each output partition depends on one input partition | `select`, `filter`, `withColumn` | None |
| Wide | Output partitions depend on many input partitions | `groupBy`, `join`, `orderBy`, `distinct` | A **shuffle** across the network |
A partition is a slice of the data that one task processes. A shuffle redistributes rows between partitions so that rows with the same key end up together. Shuffles are usually the most expensive part of a job. A job is split into stages at each shuffle boundary.
Errors show up late
Because nothing runs until an action, some mistakes appear in a different cell from the one that caused them.
Spark checks column names and types when you build the plan, a step called analysis. A misspelled column therefore fails right away, even though no data has been read.
orders.select("custmer") # AnalysisException: cannot resolve 'custmer'Errors that depend on the data itself, such as a failed cast, a bad file path in some sources, or a corrupt row, appear only when an action runs. The cell that fails is the one with the action, which may be far from the line that introduced the problem.
bad = orders.withColumn("n", F.col("customer").cast("int")) # returns immediately
bad.show() # runs nowIn the default Spark configuration, casting a non-numeric string to int gives null instead of raising an error, so bad.show() displays nulls. If ANSI mode is on, the same cast raises an error at show(). In both cases the work happens at the action.
Some operations are not purely lazy. spark.read with inferSchema set to true, for example, scans data to infer types, so it can start a job even though it returns a DataFrame. Supplying a schema avoids that scan.
Every action re-runs the plan
Without caching, each action evaluates the full chain again from the source.
big_orders.count() # job 1: reads, filters, counts
big_orders.show() # job 2: reads and filters againFor a small in-memory DataFrame this is trivial. For a large input with expensive joins, repeating the work is a common reason a notebook feels slow. Two options are available:
- Save the intermediate result to a table with
saveAsTable, then read it back. This survives cluster restarts. - Call
cache()and run an action to fill the cache. This lasts only for the current session and uses cluster memory. Thecache()call itself is lazy.
joined = orders.join(customers, on="customer", how="left")
joined.cache()
joined.count() # materializes the cache
joined.show() # reads from the cacheCaching helps only when you reuse the same result several times. If you use it once, it adds cost without benefit. Later chapters cover when to cache and how to check that it worked.
Cost of common actions
Actions differ widely in how much work they do and how much data they bring back to the driver, the machine that runs your notebook code.
| Action | Work done | Risk |
|---|---|---|
| `count()` | Runs the whole plan, returns one number | Can be slow on big inputs |
| `show(n)` / `take(n)` | Often stops after finding `n` rows | Low |
| `display(df)` | Runs the plan, returns a limited preview to the notebook | Low, but may still scan a lot |
| `collect()` | Runs the plan, returns all rows to the driver | Can run the driver out of memory |
| `write` / `saveAsTable` | Runs the plan, writes all output | Changes stored data |
Use show, take, or limit when you only want a look at the data. Reserve collect() for results you know are small, such as the output of an aggregation.
A limit is itself a transformation, so df.limit(5) returns a DataFrame. A sort followed by a limit still needs to see all the data to find the top rows, so it is not as cheap as it looks.
Seeing the plan without running it
explain() is not an action in the sense of running the query. It prints the plan that an action would execute.
big_orders.explain()Run it right after building a chain. You can check that a filter appears near the scan and that no unexpected shuffle is present. The chapter on query plans shows how to read the output in detail.
Common mistakes
- Timing a transformation. Wrapping
df.filter(...)in a timer measures only plan creation. Time the action instead. - Expecting side effects. Code inside a transformation, such as a Python function in a UDF that prints, does not run when you define it. It runs on executors when an action executes, and its output may not appear in the notebook.
- Assuming a DataFrame is a snapshot. If the source files or table change between two actions, the second action can return different results, because it re-reads the source.
- Calling
collect()to inspect. This moves all rows to the driver. Useshoworlimitfirst.
Exercise
A notebook cell builds result = df.filter(...).join(other, "id").groupBy("k").count() and finishes in under a second on a 2 TB table. The next cell runs result.show() and takes ten minutes. Why does the first cell finish so quickly, and what two things happen at show()?
Show answer
The first cell contains only transformations (filter, join, groupBy/count), so Spark only records the plan and returns a new DataFrame without reading data. At show(), which is an action, Spark first optimizes the plan (for example pushing the filter toward the scan and choosing a join strategy), then runs it as a job on the cluster. That job includes shuffles for the join and the grouping, which accounts for the ten minutes.
Exercise
You run joined.cache() and then joined.show() and joined.count() in separate cells. Which of these calls does the first full computation and fills the cache, and why is cache() alone not enough?
Show answer
The first action, joined.show(), computes the data and fills the cache. (show may compute only enough partitions to return the rows it displays, so the cache can be only partly filled; count() then computes the rest.) cache() is lazy: it only marks the DataFrame for caching, so no data is stored until an action runs.