RDDs, DataFrames and Datasets
Spark has three ways to write a job: RDDs, DataFrames and Datasets. Older tutorials and interviews still mention all three. This lesson shows what each one is, the same small job in two of them, when an RDD still makes sense, and what all three share underneath.
Step 2 · Spark internals · Bronze · How a job runs, lesson 2 of 5
On this page
Show code in
Every code block on the page follows this.
Read first: Transformations vs actions (skip if you know it)
In plain words first
Think of giving instructions to a moving company. With an RDD you hand them sealed boxes and say "carry each one, open it, and do this to whatever is inside": they cannot see what is in the boxes, so they cannot plan. With a DataFrame you hand them a labelled inventory, "200 chairs, 50 tables, only take the chairs", and they can plan the cheapest way to do it.
Spark has three APIs. RDDs are the sealed boxes, DataFrames the labelled inventory, and Datasets (Scala and Java only) a typed version of the inventory.
The three APIs
| API | What it holds | Languages | Optimised by Catalyst |
|---|---|---|---|
| RDD (2011) | Any objects; Spark does not know their structure | Scala, Java, Python | No |
| DataFrame (2015) | Rows with a known schema of named, typed columns | Scala, Java, Python, R, SQL | Yes |
| Dataset (2016) | Typed objects with a schema; a DataFrame is Dataset[Row] | Scala and Java only | Yes, except inside lambdas |
PySpark has RDDs and DataFrames. Datasets need compile-time types, which Python does not have, so in Python the DataFrame is the structured API. Spark Connect (Spark 3.4+) and serverless platforms do not support RDDs at all.
The same job twice
# RDD: Spark sees only "apply this Python function" revenue = (sales.rdd .filter(lambda r: r.amount > 0) .map(lambda r: (r.country, r.amount)) .reduceByKey(lambda a, b: a + b)) # DataFrame: Spark sees filter, group and sum revenue = (sales .filter(F.col("amount") > 0) .groupBy("country") .agg(F.sum("amount").alias("revenue")))
SELECT country, SUM(amount) AS revenue FROM sales WHERE amount > 0 GROUP BY country
When an RDD still makes sense
- Low-level control of partitioning with a custom partitioner (Scala/Java).
- Data with no tabular structure at all, processed by arbitrary code (rare; mapInPandas or a Python data source usually covers it in PySpark).
- Reading legacy code:
sc.textFile,mapPartitions,reduceByKeystill appear in older jobs and interviews. df.rdd.getNumPartitions()is still the common way to check partitionpartition: A chunk of a DataFrame's rows. Spark processes each partition as one task, so partitions decide how much work runs in parallel. Learn more → counts.
What all three share
Underneath, every DataFrame query becomes RDD operations: the physical plan is executed as RDDs of binary rows. So the core ideas are the same for all three: lazy transformationstransformation: An operation that describes a new DataFrame (filter, select, join) without running anything yet. Learn more →, actionsaction: An operation that needs a result (count, show, write), so Spark has to run the job. Learn more → that trigger jobs, lineage used to recompute lost partitions, narrow and wide dependencies, and stagesstage: A group of steps Spark can run without moving data between machines. A new stage starts at every shuffle. Learn more → split at shufflesshuffle: Moving rows between machines so that all rows with the same key end up together. Needed by joins, groupBy and sorting, and usually the most expensive step of a job. Learn more →. reduceByKey vs groupByKey is the RDD version of "aggregate before the shuffle": reduceByKey combines values on each executorexecutor: A worker process on a cluster machine that runs tasks and holds data in memory. Learn more → first; groupByKey ships every value across the network.
Try it yourself
Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.
Goal: Write a small aggregation the way it would look in a real job: DataFrame code, written to ParquetParquet: A columnar file format: values of each column are stored together, so queries read only the columns they need. Learn more →.
from pyspark.sql import functions as F sales = spark.createDataFrame( [("IN", 120.0), ("IN", -5.0), ("US", 80.0), ("DE", 40.0)], ["country", "amount"]) revenue = (sales.filter(F.col("amount") > 0) .groupBy("country") .agg(F.sum("amount").alias("revenue"))) revenue.write.mode("overwrite").parquet("lab/rdd_vs_df/revenue") spark.read.parquet("lab/rdd_vs_df/revenue").orderBy("country").show()
Output from a real run
+-------+-------+ |country|revenue| +-------+-------+ | DE| 40.0| | IN| 120.0| | US| 80.0| +-------+-------+
What to notice:
- India's revenue is 120.0, not 115.0: the
-5.0row was filtered out before summing. - Three countries in, three rows out: one per group.
Common mistakes
- Converting to an RDD to do something a DataFrame can do —
df.rdd.map(...)loses all optimisation and adds Python serialisation. - Thinking Datasets exist in PySpark — They are Scala/Java only; in Python, a DataFrame is the structured API.
Key takeaways
- RDDs are collections of opaque objects; DataFrames are typed tables Spark understands.
- Datasets are Scala/Java only; in Python the DataFrame is the structured API.
- Use an RDD only for legacy code or low-level control; everything tabular belongs in a DataFrame.
- All three share lineage, lazy transformations, actions and stages split at shuffles.
Interview prep
THE QUESTION
"RDD vs DataFrame: which do you use and why?"
Avoid: "DataFrames are faster" without saying why: Catalyst optimises the plan and Tungsten keeps rows in compact binary form, which an RDD of objects cannot get.
Follow-ups · answer out loud, then open
Follow-up"Why is a Python RDD map so much slower than the same logic as DataFrame functions?"
Scenario"You inherit an RDD job that parses logs with regexes and aggregates them. How would you modernise it?"
spark.read.text), parse with regexp_extract or split, then aggregate with groupBy. Keep a UDF only for logic built-ins cannot express. Validate by comparing outputs on a sample, then compare runtime and shuffle sizes in the Spark UI.Trap"Datasets are type-safe, so PySpark users should use Datasets."
map calls.Check yourself
3 questionsWhich API is not available in PySpark?
Show the answer
Dataset. Typed Datasets need compile-time types, available in Scala and Java.
What happens to a lost partition of a DataFrame on a failed executor?
Show the answer
Spark recomputes it from its lineage. Every API shares lineage: Spark replays the steps that built the lost partition.
Which is a fair reason to still use an RDD today?
Show the answer
Reading legacy code, or custom partitioning in Scala/Java. Everything tabular is faster as a DataFrame; RDDs remain for legacy code and low-level control.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · How a job runs · lesson 3 of 5 · 8 min readWhy DataFrames are faster than RDDs
Column pruning, pushdown, no Python round trip, Tungsten rows and code generation: five reasons, and how one lambda switches them off.
Related lessons
Transformations vs actionsSpark internals · 6 min read
Catalyst and physical plans
Previous: Transformations vs actions
Primary sources: RDD programming guide · SQL, DataFrames and Datasets