beginner
Creating RDDs
8 min readLast updated: 2026-07-08
Overview
Learn the two primary ways to create RDDs: by parallelizing local memory collections or by reading external files.
What You Will Learn
In this lesson, you will learn:
- Parallelize Collection: Converting local arrays to distributed RDDs.
- Read Files: Loading text files using
textFile(). - Configure Partitions: Setting partition counts manually.
Detailed Concept Explanation
You can initialize RDDs in two ways:
sc.parallelize(collection, partitions): Takes a local memory list or collection and distributes it across worker executors.sc.textFile("path"): Reads a text file (from local disk, HDFS, or cloud storage) and creates an RDD where each record represents a line of text.
Code Examples
Python (PySpark) Implementation
python
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("CreateRDD").getOrCreate()
sc = spark.sparkContext
# Method 1: Parallelize local list
rdd1 = sc.parallelize(["London", "Paris", "Berlin"], numSlices=2)
# Method 2: Read external text file
# rdd2 = sc.textFile("cities.txt")
print("Partitions Count:", rdd1.getNumPartitions())
Expected Output
text
Partitions Count: 2
Execution Plan Diagram (Python & Scala)
Execution Plan Diagram
SparkContext.parallelize(numSlices=2)
getNumPartitions()
print()
Scala Implementation
scala
import org.apache.spark.sql.SparkSession
val spark = SparkSession.builder().appName("CreateRDDScala").getOrCreate()
val sc = spark.sparkContext
val rdd = sc.parallelize(Seq("London", "Paris", "Berlin"), numSlices = 2)
println(s"Partitions Count: ${rdd.getNumPartitions()}")
Expected Output
text
Partitions Count: 2
SQL Perspective
SQL Query Support:
Since RDDs are unstructured collections, they cannot be queried via SQL directly. You must convert them to structured DataFrames:
python
df = rdd1.map(lambda x: (x,)).toDF(["city"])
df.createOrReplaceTempView("cities_table")
spark.sql("SELECT * FROM cities_table").show()
Common Mistakes
- Parallelizing Massive Lists: Attempting to parallelize a massive dataset (e.g. 50GB list in Python memory) using
parallelize(). This will overload the driver node. UsetextFileor load from databases directly.
Best Practices
- Specify numSlices: Always specify the partition count parameter (
numSlicesorminPartitions) explicitly to balance the work across executors.
Interview Perspective
What is the difference between parallelize() and textFile() in Spark?
parallelize() distributes a local memory collection from the driver node across the executors, which is useful for testing. textFile() reads files directly from distributed storage (like HDFS or S3) into executors, which scales to very large datasets.