Before you use this reference
This page is a lookup, not a tutorial. The explanations live in Distributed Processing Fundamentals, Lazy Evaluation and the DAG, DataFrames and the Catalyst Optimizer, Partitioning in Spark, Transformations, Actions, and Shuffles, Reading and Writing Data at Scale, and PySpark Performance Pitfalls.
Transformations vs. actions#
Transformation (lazy, builds the plan): filter, select, groupBy, joinAction (triggers execution): count, collect, show, writeNarrow vs. wide transformations#
| Type | Examples | Data movement |
|---|---|---|
| Narrow | filter, select, withColumn | None — each partition computed independently |
| Wide | groupBy, join, distinct, repartition | Shuffle — data moves across the network |
DataFrame vs. RDD#
RDD: arbitrary Python functions, opaque to the optimizerDataFrame: named columns + structured ops -> Catalyst can optimizePrefer the DataFrame API; drop to RDDs only when nothing else expresses the operation.
Reading and writing#
# Explicit schema — skips the extra inference passdf = spark.read.csv("orders.csv", header=True, schema=schema)
# Partitioned write, with an explicit modedf.write.mode("overwrite").partitionBy("year", "month").parquet("output/")| Mode | Behavior |
|---|---|
overwrite | Replace existing data |
append | Add alongside existing data — not automatically idempotent |
errorIfExists | Fail if the destination already has data (default) |
Partition sizing#
Default spark.sql.shuffle.partitions = 200 — check it, don't trust it.Target: ~2-4 partitions per CPU core, ~128MB-1GB of data per partition.
repartition(n): full shuffle, even split, can increase or decrease countcoalesce(n): merges adjacent partitions, cheaper, decrease onlyAvoiding a shuffle: broadcast join#
from pyspark.sql.functions import broadcastresult = big_df.join(broadcast(small_df), "key")Three pitfalls to check first#
.collect() on an unbounded result: can OOM the driverPython UDF instead of a built-in: opaque to Catalyst + serialization costData skew: one oversized partition dominates a stageFurther reading#
- Apache Spark and the PySpark API Reference — the full official documentation this page summarizes.
- Performance Tuning — Spark SQL documentation — shuffle partitions, broadcast thresholds, and Adaptive Query Execution.
- PySpark SQL Functions Reference — the built-in function library to check before writing a UDF.
- Out of memory — the
failure mode an unbounded
.collect()risks on the driver.