Sub topic 5
Transformations, actions and lazy evaluation
This chapter assumes you can run a Databricks notebook cell, know what a DataFrame is, and have used spark and display. It explains why some lines of Spark code finish instantly and others start a job.
Two kinds of operations
Every DataFrame operation is either a transformation or an action.
- A transformation returns a new DataFrame and describes a step. Examples:
filter,select,withColumn,groupBy().agg(),join. - An action asks Spark for a result, so it must do the work. Examples:
show,count,collect,display, and writing withsaveAsTable.
Spark is lazy. A transformation only adds a step to a logical plan. Nothing is read or computed until an action runs. Spark then optimizes the whole plan and executes it as a job.
A worked example
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",
)
orders = orders.withColumn("order_date", F.to_date("order_date"))
big_orders = (
orders
.filter(F.col("amount") > 50)
.select("order_id", "customer", "amount")
.withColumn("amount_rounded", F.round("amount"))
)
big_orders.show()The chain of filter, select and withColumn runs almost instantly because it only builds a plan. The show() call is the action. It triggers the job and prints the rows.
Consequences of laziness
- Errors can appear late. A misspelled column name is usually caught when the plan is analyzed, but a bad file path or a data problem may only fail at the action.
- Each action re-runs the plan. If you call
count()and thenshow()on the same DataFrame, Spark computes it twice unless you cache it. Caching is covered in a later chapter. - Optimization is free. Because Spark sees the whole plan, it can push the filter down toward the data source and read only the columns it needs.
- Timing is misleading. A slow cell is usually the action, not the transformation lines above it.
Common mistakes
- Expecting a transformation to change a DataFrame in place. DataFrames are immutable, so
orders.filter(...)on its own line does nothing unless you assign the result. - Calling
count()after every step to "check progress". Each call runs a full job. - Treating a fast cell as proof that the code is correct. It may not have run yet.
Exercise
You run df2 = df.filter(F.col("amount") > 50) and the cell finishes in milliseconds, even though df is very large. Then df2.count() takes a minute. Why?
Show answer
filter is a transformation, so it only adds a step to the plan and does no work. count() is an action, so it triggers Spark to read the data, apply the filter and count the rows, which takes the time.
Exercise
Which of these are actions: select, show, withColumn, count, join?
Show answer
show and count are actions. select, withColumn and join are transformations.