Spark DataFrame API
Use PySpark to clean, join, and aggregate records. Read an execution plan and reason about when Spark moves data between workers.
Spark building blocks
Spark is made of libraries on top of one engine. Spark Core is the engine and low-level API (Python, SQL, Scala, Java, R). Spark SQL adds DataFrames and SQL. Structured Streaming handles streams (it replaced the legacy DStream "Spark Streaming"). MLlib is the machine learning library and GraphX the graph library. The old "100x faster than Hadoop in memory" figure is a historical benchmark, not something the exam tests.
PySpark is the Python API for Spark. A PySpark DataFrame looks like pandas but is distributed across the cluster, and you can mix it with SQL through spark.sql(...).
RDDs
An RDD (Resilient Distributed Dataset) is Spark's original low-level, immutable distributed collection. DataFrames are built on top of it and are optimized by Catalyst, so prefer DataFrames. RDD functions you may see in options: map, flatMap, filter, distinct, reduce, reduceByKey, count, first, take, countByValue, sortBy, groupBy.
rdd = spark.sparkContext.textFile("/Volumes/main/raw/landing/book.txt")
counts = (rdd.flatMap(lambda line: line.split(" "))
.map(lambda w: (w, 1))
.reduceByKey(lambda a, b: a + b))
RDD APIs are not supported on serverless compute or on Standard (shared) access mode clusters.
How Spark executes code
- A DataFrame is an immutable, distributed table with a schema. Each transformation returns a new DataFrame.
- Transformations (
select,filter,join,groupBy) are lazy: they build a plan. Actions (count,collect,show,display,write) trigger execution. - The Catalyst optimizer turns the plan into physical steps. See it with
df.explain(). - An action creates a job. A job is split into stages at each shuffle boundary. A stage runs as tasks, one per data partition, on executor cores.
- Narrow transformations (
filter,select,withColumn) work within a partition. Wide ones (groupBy,join,distinct,orderBy) need a shuffle, moving data across the network. Shuffles are the main cost.
Reading and writing
df = spark.read.table("main.bronze.orders") # or spark.table(...)
df = spark.sql("SELECT * FROM main.bronze.orders")
df = (spark.read.format("csv").option("header", True)
.option("inferSchema", True).load("/Volumes/main/raw/landing/orders/"))
df.write.mode("overwrite").saveAsTable("main.silver.orders") # modes: append, overwrite, ignore, error/errorifexists (default)
Cleaning bronze into silver
from pyspark.sql import functions as F
silver = (spark.read.table("main.bronze.orders")
.filter(F.col("order_id").isNotNull()) # drop rows missing the key
.withColumn("amount", F.col("amount").cast("decimal(10,2)")) # standardize types
.withColumn("order_ts", F.to_timestamp("order_ts", "yyyy-MM-dd HH:mm:ss"))
.withColumn("country", F.upper(F.trim("country")))
.fillna({"channel": "unknown", "discount": 0}) # replace nulls per column
.dropDuplicates(["order_id"]))
silver.write.mode("overwrite").saveAsTable("main.silver.orders")
| Null handling | Effect |
|---|---|
df.na.drop() / dropna(how="any") | Drop rows with any null. how="all": only rows where all columns are null. subset=[...] limits columns. thresh=n keeps rows with at least n non-null values. |
df.na.fill(0) / fillna({...}) | Replace nulls (value type must match column type) |
F.coalesce(a, b, F.lit(0)) | First non-null value |
col.isNull(), isNotNull() | Filter on nulls. col == None does not work: comparisons with null return null. |
Column and row manipulation
df.select("id", F.col("name").alias("customer_name"))
df.withColumn("total", F.col("qty") * F.col("price")) # add or replace a column
df.withColumnRenamed("cust_nm", "customer_name")
df.withColumnsRenamed({"a": "x", "b": "y"})
df.drop("tmp_col", "other")
df.filter((F.col("country") == "FR") & (F.col("amount") > 100)) # same as .where(); use & | ~
df.withColumn("parts", F.split("full_name", " ")) # string -> array
.withColumn("first", F.col("parts")[0]) # or F.split(...).getItem(0)
df.withColumn("item", F.explode("items")) # one row per array element; drops null/empty arrays
df.withColumn("item", F.explode_outer("items")) # keeps rows with null/empty arrays
df.select("order.id", "order.customer.name") # struct fields with dot notation
df.withColumn("status", F.when(F.col("amt") > 0, "paid").otherwise("free"))
df.orderBy(F.col("amount").desc()).limit(10)
Arrays: explode, flatten and helpers
explode adds rows (one per array element, or one per key/value for a map). flatten turns an array of arrays into one array and keeps the row count. Both are built-in Spark SQL functions. Other array helpers: sort_array(a), element_at(a, 1) (1-based; negative counts from the end).
Dates, strings and regex
-- SQL
SELECT year(order_ts), month(order_ts), dayofmonth(order_ts),
regexp_extract(email, '@(.*)$', 1) AS domain
FROM main.silver.orders;
# PySpark: same function names
df.select(F.year("order_ts"), F.month("order_ts"), F.dayofmonth("order_ts"),
F.regexp_extract("email", r"@(.*)$", 1).alias("domain"))
Combining DataFrames
orders.join(customers, on="customer_id", how="inner") # default how is inner
orders.join(customers, on=["customer_id", "region"], how="left") # multiple keys
orders.join(customers, orders.cust == customers.id, "left") # different key names
orders.join(F.broadcast(countries), "country_code") # broadcast join hint
sizes.crossJoin(colors) # cartesian product
df1.union(df2) # by POSITION, keeps duplicates (like SQL UNION ALL)
df1.unionByName(df2, allowMissingColumns=True) # by column NAME
df1.union(df2).distinct() # like SQL UNION
| Join type | Returns |
|---|---|
| inner | Rows with a match on both sides |
| left / left_outer | All left rows; right columns null when no match |
| right, full / outer | All right rows; all rows from both |
| left_semi | Left rows that have a match (no right columns). Like WHERE EXISTS. |
| left_anti | Left rows with no match. Like WHERE NOT EXISTS. Good for finding new records. |
| cross | Every combination (rows = left × right) |
Broadcast join: Spark copies a small table to every executor so the large table does not need to be shuffled. Spark does it automatically when a side is smaller than spark.sql.autoBroadcastJoinThreshold (default 10 MB). A broadcast that is too big can cause driver or executor out-of-memory errors.
Deduplication and aggregation
df.distinct() # full-row duplicates
df.dropDuplicates(["order_id"]) # duplicates on key columns (keeps an arbitrary row)
# keep the latest row per key
from pyspark.sql.window import Window
w = Window.partitionBy("order_id").orderBy(F.col("updated_at").desc())
latest = df.withColumn("rn", F.row_number().over(w)).filter("rn = 1").drop("rn")
(df.groupBy("country")
.agg(F.count("*").alias("orders"),
F.countDistinct("customer_id").alias("customers"),
F.approx_count_distinct("customer_id").alias("customers_approx"), # HyperLogLog, much faster
F.sum("amount").alias("revenue"),
F.avg("amount").alias("avg_amount"), # mean
F.max("order_ts").alias("last_order")))
df.describe("amount").show() # count, mean, stddev, min, max
df.summary().show() # adds 25%, 50%, 75% percentiles
df.count() # number of rows (action)
F.count("col") skips nulls; F.count("*") counts every row. approx_count_distinct trades a small error (default relative standard deviation of 5%) for speed on large data.
User-defined functions
from pyspark.sql.types import StringType
@F.udf(returnType=StringType())
def mask_email(e): return None if e is None else e[0] + "***@" + e.split("@")[1]
df.withColumn("email_masked", mask_email("email"))
spark.udf.register("mask_email", mask_email) # make it callable from SQL
Python UDFs are slow (row-by-row serialization between JVM and Python). Prefer built-in functions; if you need Python, prefer pandas UDFs (@F.pandas_udf), which are vectorized with Apache Arrow.
Basic tuning parameters New exam
| Parameter | Default | What it controls |
|---|---|---|
spark.sql.shuffle.partitions | 200 | Number of partitions after a shuffle in DataFrame/SQL operations (joins, groupBy). Too high: many tiny tasks. Too low: huge partitions, spills, skew pain. Adaptive Query Execution (AQE, on by default) coalesces shuffle partitions automatically; you can also set it to auto on Databricks. |
spark.default.parallelism | Total executor cores | Default number of partitions for RDD operations (e.g. parallelize). Does not affect DataFrame shuffles. |
spark.executor.memory / spark.driver.memory | Set by node type | Heap memory per executor or driver. Raise (or choose larger or memory-optimized nodes) for OOM and spill. Set in cluster config, not at runtime. |
spark.sql.autoBroadcastJoinThreshold | 10 MB | Max size of a table to broadcast automatically. -1 disables auto broadcast. |
spark.conf.set("spark.sql.shuffle.partitions", 64)
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", 50 * 1024 * 1024)
spark.conf.get("spark.sql.shuffle.partitions")
Method the exam expects: change one parameter, re-run and re-measure (wall time, stage times in the Spark UI), keep it only if it helps. Serverless compute manages most of these for you and does not allow setting many of them.
Other tools: df.repartition(n, "col") (full shuffle, can increase partitions), df.coalesce(n) (reduce partitions without a full shuffle), df.cache() / persist() for reused DataFrames.
Spark cache statements (SQL)
The SQL counterparts of df.cache() are the statements below.
| Statement | Effect |
|---|---|
CACHE [LAZY] TABLE t [OPTIONS ('storageLevel' 'MEMORY_ONLY')] [AS SELECT ...] | Caches a table or query result. Caching a query creates a temp view named t. Avoids re-scanning source files. |
UNCACHE TABLE [IF EXISTS] t | Removes one table or view from the cache |
CLEAR CACHE | Removes every cached table and view |
REFRESH TABLE t | Invalidates cached data and metadata for t. The cache is refilled lazily the next time t is queried. Use it when files under a table changed outside Spark. |
REFRESH 'path' | Invalidates cached data for every dataset whose source path starts with that prefix |
REFRESH FUNCTION f | Invalidates the cached entry of a permanent function (not temporary ones) |
After source files change outside Spark, REFRESH TABLE invalidates cached data and metadata. The next query repopulates the cache as needed. Serverless compute and SQL warehouses manage caching automatically, so these statements mainly apply to classic clusters.
Select the latest event
A device emits three records with the same ID and different timestamps. Explain why dropDuplicates on the ID alone cannot promise to retain the newest event.
Check your reasoning
It can keep any matching row. Use a window partitioned by device ID and ordered by descending event time, then keep row number 1. Add a deterministic tie-breaker if event times can match.
Product reference
Spark DataFrame API quiz
Answer 8 questions. Check each answer for an explanation.