Tutorial 4: MapReduce & PySpark
pyspark · SparkContext · RDDs · Submit as dm04t[RR].py
pip install pyspark. PySpark requires Java (JDK 8 or 11). If you run into setup problems, come to office hours before the deadline.
Submission
Name your file dm04t[RR].py where RR = last two digits of your roll number. All tasks in one file with # Task N comments. Submit by the deadline announced in class.
Background
MapReduce is a programming model for processing large datasets in parallel. The Map step applies a function to each input record, emitting (key, value) pairs. The Reduce step groups by key and aggregates. PySpark is Apache Spark's Python API: it implements MapReduce-style processing through Resilient Distributed Datasets (RDDs), a fault-tolerant distributed collection. In this tutorial you will run Spark locally (one machine, multiple cores) and experience the RDD API before we scale to clusters.
We work with a small text dataset so you can trace every step by hand and verify the output.
Tasks
Task 1 Start a SparkContext and Verify Setup
- Import:
from pyspark import SparkContext, SparkConf - Create a SparkConf for a local run:
conf = SparkConf().setMaster("local[*]").setAppName("DM Tutorial 4") sc = SparkContext(conf=conf)
- Print the Spark version:
print(sc.version) - Print the default parallelism (number of local cores detected):
print(sc.defaultParallelism)
"local[*]" tells Spark to use all available CPU cores on your machine. In production, you replace this with the cluster master URL.Task 2 Create an RDD and Explore It
We will use a list of sentences as our input dataset.
- Define:
sentences = [ "data mining scales to large data", "large data needs distributed processing", "mapreduce splits data into map and reduce", "spark is faster than mapreduce for iterative jobs", "data streams require online processing algorithms" ]
- Create an RDD:
rdd = sc.parallelize(sentences) - Print the number of partitions:
print(rdd.getNumPartitions()) - Print the first element:
print(rdd.first()) - Print all elements:
print(rdd.collect())
Task 3 Map Step: Tokenise Each Sentence
The Map step transforms each record. Here we split each sentence into (word, 1) pairs: the classic word count setup.
- Use
flatMapto emit one (word, 1) pair per word across all sentences:pairs = rdd.flatMap(lambda sentence: [(word, 1) for word in sentence.split()]) - Print the count of pairs:
print(pairs.count()) - Print the first 10 pairs:
print(pairs.take(10))
flatMap vs map: map returns one item per input item; flatMap returns zero or more: it flattens lists from each call into one RDD.Task 4 Reduce Step: Count Words
- Group by key and sum:
word_counts = pairs.reduceByKey(lambda a, b: a + b) - Collect the results and sort by count descending
- Print the top 10 most frequent words
reduceByKey is the Reduce step: Spark automatically groups all (key, value) pairs with the same key and applies your function to combine values.Task 5 Filter: Words that Appear More than Once
- Filter the word_counts RDD to keep only words with count > 1:
word_counts.filter(lambda x: x[1] > 1) - Print these repeated words sorted alphabetically
Task 6 Extension: MapReduce Pipeline on Numerical Data
Create a list of 1000 random integers between 0 and 99 using import random; nums = [random.randint(0, 99) for _ in range(1000)]. Parallelise into an RDD. Use map to label each number as "even" or "odd". Use countByKey() to count how many are even vs odd. Print the result. Then stop the SparkContext: sc.stop().
sc.stop() at the end of your script: leaving the SparkContext running keeps a web server alive on your machine.