Lecture 9 - Realtime Processing with Spark
Roadmap — Spark Fundamentals
- Why Apache Spark?
- Spark Architecture and Execution
- Spark Deployment Mode
- Resilient Distributed Datasets (RDD)
- Transformations
- Actions
- Lazy Evaluation, Lineage
- Spark using Python (PySpark)
- Running on AWS EMR
Why Spark for Big Data Processing? (The Problem with Disk-Based Processing)
- Hive is a pure data warehousing database which stores data in the form of tables
- It can only process structured data, read and written using SQL
- Hive is not for unstructured data
- Only runs with YARN as the processing engine
- It stores intermediate files on disk → needs a lot of I/O
- Apps reload data from stable storage on each query → no good for reuse

Disk-based processing is like a chef who puts every half-cooked dish back into the fridge after each step, then takes it out again for the next step. Every trip to the fridge (disk) wastes time.
Why Spark for Big Data Processing? (Spark's Answer)
- Spark supports efficient data reuse through in-memory caching while maintaining fault tolerance and scalability
- Still maintains Fault tolerance, Data locality, Scalability
- Does Spark always process everything in memory?
- No (some operations still need to read/write disk)

Spark is the chef who keeps everything on the counter (RAM) while cooking. Only if the counter gets full (or a step really needs it, like a shuffle) does something go back into the fridge (disk).
Apache Spark Overview
- It is a unified analytics engine for large-scale data processing with:
- Batch and Real-time processing
- Stream Analytics
- Supports Machine Learning, Interactive SQL
- Natively Spark supports Scala, Python, Java and an interactive shell
- Well integrated with the Hadoop ecosystem and data sources

- Key features shown on the slide:
- Speed
- Fault Tolerance
- Lazy Evaluation
- Dynamic nature
- Multiple Language Support
- Reusability
- Machine Learning
- Graph Processing
- Real-Time Stream Processing
"Unified" = one Swiss Army knife instead of a separate tool for batch (MapReduce), SQL (Hive), ML, and streaming.
Spark in the Big Data Ecosystem
- Layers (top → bottom):
- Applications / Analytics: SQL · ETL · Machine Learning · Streaming
- ↓
- Apache Spark Processing Engine
- ↑↓
- Storage / sources: HDFS / S3, Hive Tables, Databases

Spark is the engine in the middle: it does not store data itself, it reads from storage (HDFS, S3, Hive, databases) and serves results to applications.
Apache Spark Architecture
- Spark Core provides the in-built memory computing and referencing datasets stored in external storage systems
- It is Spark Core's responsibility to perform all the basic I/O functions, scheduling, monitoring:
- Memory management and recovery after failures
- Planning, distribution, and tracking of tasks in a cluster
- Interaction with storage systems
- Resilient Distributed Datasets (RDDs)

- Layers of the stack:
- Programming Language: Scala, R, Java, Python
- Libraries: Spark SQL, MLlib, GraphX, Streaming
- Engine: Spark Core
- Cluster Management: Hadoop YARN, Apache Mesos, Spark Scheduler
- Storage: HDFS, Standalone Node, Cloud, RDBMS/NoSQL
Apache Spark Component

- Streaming sources include Kafka, Flume, Twitter, HDFS and ZeroMQ
- Spark Streaming
- Uses DStreams to periodically create RDDs
- Can use machine learning models to analyze streaming data
- Can use GraphX features on the data it receives
- Spark ML & MLlib
- Spark MLlib models use DataFrames to represent data; Spark ML uses RDDs. Both use features from Spark Core
- Spark GraphX (Graph RDD) uses Spark Core features behind the scenes
- Spark SQL (DataFrame) transforms operations on DataFrames into operations on RDDs
- Spark Core (RDD) is at the center — everything is built on it
- Filesystems include HDFS, Gluster FS, Amazon S3 and others
- Data sources include Hive, JSON, relational databases, NoSQL databases, Parquet files and others
Spark Core + RDD is the foundation of a building; Streaming, MLlib, GraphX and SQL are different floors built on top of it.
Spark Job Execution
- SparkContext coordinates the execution of Spark applications by communicating with the cluster manager and scheduling tasks across executors
- Flow: Code → Spark Application → Driver Program (contains Spark Context) → Spark Context → Cluster Manager → Worker Nodes
- The Driver Program:
- Coordinates
- Schedules Job
- Inside the Spark Context:
- DAG Scheduler (DAG = Directed Acyclic Graph) splits a Job into Stages (S-1, S-2, S-3) connected by Tasks (T)
- Task Scheduler sends the tasks to the Cluster Manager
- Legend: S: Stages, T: Tasks

The driver is the project manager: it turns your code into a plan (DAG), cuts the plan into phases (stages) and small to-do items (tasks), then hands them to workers through the cluster manager.
Understanding Job, Stage, and Task
- Application: An entire Spark program. It includes both the Driver and the Executors
- Job: A Job is created only when an Action is triggered (such as
count()orcollect()) - Stage: When a Job starts, it is broken down into Stages
- A Shuffle Boundary occurs when data must be moved across the network, which forces the creation of a new Stage
- Hierarchy:
- One Application → Multiple Jobs → Multiple Stages → Multiple Tasks

A school year (application) has several exams (jobs). Each exam has sections (stages) — you can't start section 2 until all papers from section 1 are collected and re-sorted (shuffle). Each section is graded by many teachers in parallel (tasks).
How Partitions Enable Parallelism
- Scenario: Input file contains 1,000,000 records stored in 4 Partitions, Spark has 2 Task Slots
- Partitions represent the logical division of your data
- CPU cores or slots represent your physical computing resources
- Spark processes the data by assigning tasks to the available slots in multiple rounds, or 'waves', until all tasks are completed
- Can Spark run all 4 tasks at the same time? No…
- Wave 1: Task Slot 1 executes Task 1, Task Slot 2 executes Task 2
- Wave 2: Task Slot 1 executes Task 3, Task Slot 2 executes Task 4

- Example: waves
4 loads of laundry but only 2 washing machines → you need 2 rounds.
Spark Architecture Components
- Spark is a distributed computing framework that we can run in several modes, ranging from a single machine to a large-scale cluster of machines
- Spark App (Driver Program)
- Each SparkContext creates a Spark application, which includes a lot of scheduling components
- Upon an Action, the driver program submits the job to the cluster manager
- Cluster manager (Scheduler) → task scheduler, resource allocation, monitor workflow
- Starts executors on Worker Nodes
- It does not know about stages
- Worker → perform actual task, execute command from driver
- Launches a Spark Executor in a process (with a Cache)
- Tasks are launched in separate threads, one per each core on the worker node (can be configured)

Spark Deployment Modes
- Spark deployment modes define where the Driver program runs relative to the cluster resources, fundamentally impacting application resilience, networking, log management
- Spark can be deployed in local, client and cluster mode

| Mode | Where is the Driver? | Where are Executors? |
|---|---|---|
| Local | Single machine | Local threads on the same machine |
| Client | Your machine | Workers in the cluster |
| Cluster | Inside a worker in the cluster | Other workers in the cluster |
Spark Deployment Modes: Terminology
- Resource Manager is responsible for allocating resources to Spark applications running on a cluster
- Spark has a pluggable architecture that allows different cluster managers to be used as resource managers, such as YARN
- Application Master is a program that is responsible for managing a specific Spark application running on a cluster
- It is allocating resources, coordinating tasks, fault tolerance and reporting the status of the Spark application to the Driver program
- Container represents a virtual machine, or a process, that runs on a node in the cluster and is assigned a certain amount of resources to execute the tasks or the executor
- Containers are created by the resource manager, such as YARN
- Executor is a process that runs on a worker node in a cluster and is responsible for executing tasks
- It's launched by the Application Master and is responsible for processing the data and performing computations
Think of a hotel: the Resource Manager is the front desk giving out rooms, the Application Master is the tour leader managing one tour group, a Container is a room with a fixed amount of space, and the Executor is the guest doing the actual work in that room.
Spark Deployment Modes: Local
- Spark runs on a single machine, using all the cores of the machine
- It is the simplest mode of deployment and is mostly used for testing and debugging
- Driver, Executors, and local cluster manager all run within a single JVM on a single machine
- The parallelism is achieved using the machine's local CPU threads (e.g., setting
local[4]uses 4 threads) - Supports multiple tasks based on CPU cores

Spark Deployment Modes: Client
- When you start a spark shell, the application driver creates the spark session in your local machine, which requests the Resource Manager in the cluster to create a YARN application
- The Resource Manager starts an Application Master (AM container)
- For client mode, the Application Master acts as the Executor launcher
- Executors run on the worker nodes (Container) inside the cluster
- Good for interactive development and exploratory data analysis (Jupyter NB)

Spark Deployment Modes: Client (Failure Behavior)
- The Spark application is tightly coupled to the submitting machine
- If that machine disconnects from the network, or crashes, the job fails because the Driver is lost
- A failed Spark driver process will not be retried in client deploy mode
- Also, when the client loses connectivity with YARN, your job will be killed

Client mode is like controlling a drone with a remote: if your remote (laptop) loses signal, the drone (job) falls.
Client Mode: When to Use It
- Good if you are running only one or two Spark applications at a time in a cluster
- Not ideal if running multiple applications at the same time on the same cluster, since all those Spark drivers running on a single master/remote node can lead to resource contention
- You want to be more in control of your Spark driver configurations
- In client mode, Spark driver resources will not compete with YARN resources and can be adjusted separately without affecting the YARN resource procurement of your applications
- You want to write output to the console, i.e., send the results back to the client program where you submitted your application
- Notebook applications such as Jupyter, Zeppelin etc. will use client deploy mode
Spark Deployment Modes: Cluster
- Driver is submitted to the cluster and runs as a process inside one of the worker nodes
- The Cluster Manager allocates resources for both the Driver and the Executors
- The Application Master will create the driver in it, and the driver will reach to the Resource Manager
- For Production systems, cluster mode is the best choice
- The submitting machine is only responsible for handing the application over to the cluster
- Once submitted, the user can safely disconnect

Spark Deployment Modes: Cluster (Detailed Flow)
- The Spark driver will be located within the Application Master (AM) container from YARN, regardless of where you submit your Spark application from

- Example
spark-submitcommand (cluster mode):
./bin/spark2-submit \
--master yarn \
--deploy-mode cluster \
--driver-memory 8g \
--executor-memory 16g \
--executor-cores 2 \
--py-files file1.py,file2.py,file3.zip, file4.egg \
wordByExample.py [application-arguments]- Once submitted, user can safely disconnect
Cluster mode is like mailing a package: once the post office (cluster) has it, you can go home — they handle the delivery without you.
Cluster Mode: When to Use It
- Production environments, heavy batch processing, and scheduled workloads managed by resource schedulers like YARN or Slurm
- You are submitting multiple applications at the same time or have higher application or EMR step concurrency
- While running multiple applications, Spark drivers will be spread across the cluster since the AM container from a single application will be launched on one of the worker nodes
- You are saving results in S3/HDFS and there is no need to print output to console
- You want to specify detailed instructions on where the AM runs
- You can launch AMs on CORE partition or both CORE and TASK partitions based on where you want your AM and executors to launch
- For example, you can run the AM on only on-demand CORE nodes and executors only on spot task nodes
| Client Mode | Cluster Mode | |
|---|---|---|
| Driver location | Submitting machine | Inside the cluster (AM container) |
| If client disconnects | Job fails | Job keeps running |
| Output | Console (back to client) | S3 / HDFS / logs |
| Best for | Interactive work, Jupyter, 1–2 apps | Production, many apps, scheduled jobs |
Apache Spark: Example (Word Count)
- Remember word count?
- Input (plain text):
spark is fast
spark is distributed
big data with spark- Expected Output:
spark 3
is 2
fast 1
distributed 1
big 1
data 1
with 1
- Spark version (Scala) — only 3 lines:
val textFile = sc.textFile("hdfs://...")
val counts = textFile.flatMap(line => line.split(" ")).map(word => (word, 1)).reduceByKey(_ + _)
counts.saveAsTextFile("hdfs://...")Same job, ~48 lines of Java MapReduce vs 3 lines of Spark — like writing a full letter vs sending a text message.
Roadmap — Spark Fundamentals (Progress)
Why Apache Spark?Spark Architecture and ExecutionSpark Deployment Mode- Resilient Distributed Datasets (RDD) ← now
- Transformations
- Actions
- Lazy Evaluation, Lineage
- Spark using Python (PySpark)
- Running on AWS EMR
Spark Data Abstractions
- RDDs (Resilient Distributed Datasets) are typically used for application-level programming and unstructured workloads where a schema or specific class declaration is not required
- DataFrames help with a schema structure and columnar or row-level access to the data
- Formatted data sets offer benefits due to the serialization of the data being moved
- Improvement in performance when moving large volumes of data through a cluster

| RDD | DataFrame | Dataset |
|---|---|---|
| Unstructured data workloads | Structured tabular data | Strongly typed objects |
| Low-level API control | SQL-style querying | Java and Scala only |
| No schema required | Python & R default | Compile-time safety |
RDD = a box of loose items (you handle each one yourself). DataFrame = an Excel sheet with named columns. Dataset = an Excel sheet where every column also has a strict, checked type.
Resilient Distributed Datasets (RDD)
- RDD is a fundamental data structure of Spark
- It is an immutable (read-only) distributed collection of objects
- Each dataset in an RDD is divided into logical partitions, which may be computed on different nodes of the cluster
- RDDs can contain any type of Python, Java, or Scala objects, including user-defined classes
- Properties of RDD:
- Immutable
- Can be cached or persisted
- Computed lazily
- Know who their parents are
- Automatically recover from failures

- The name explained:
- Resilient → fault-tolerant; can be rebuilt from lineage if a partition is lost
- Distributed → split into partitions across nodes
- Dataset → a collection of records
An RDD is like a recipe-tracked cake cut into slices on different plates. You can't change a slice (immutable); if one plate drops, you can bake that slice again because you know the recipe and ingredients (parents/lineage).
RDD Creation
- First, you need to create a SparkSession, which is an entry point to the PySpark application
- SparkSession can be created using the
builder()ornewSession()methods of SparkSession
- SparkSession can be created using the
# Import SparkSession
from pyspark.sql import SparkSession
# Create SparkSession
spark = SparkSession.builder.master("local[*]") \
.appName("SparkByExamples.com") \
.getOrCreate()master(...)options:local[*]= use all CPU coreslocal[2]= use 2 coresyarn= use YARN/Hadoop
- There are two ways to create an RDD: Parallelizing collections and reading data from source files
# Create RDD from parallelize
dataList = [("Java", 20000), ("Python", 100000), ("Scala", 3000)]
rdd=spark.sparkContext.parallelize(dataList)# Create RDD from external Data source
rdd2 = spark.sparkContext.textFile("/path/test.txt")Controlling RDD Partitions
- Distributing data across the cluster manually
# 1. Create SparkSession (Entry Point)
from pyspark.sql import SparkSession
spark = SparkSession.builder.master("local[2]")
.getOrCreate()
# 2. Parallelize with exactly 2 partitions
data = [10, 20, 30, 40]
rdd = spark.sparkContext.parallelize(data, 2)
# 3. Check number of partitions
print("Count:", rdd.getNumPartitions())
# 4. View data inside each partition
print("Data :", rdd.glom().collect())- Output:
> Count: 2
> Data : [[10, 20], [30, 40]]
glom()returns a list of arrays, revealing exactly how elements are grouped by partition
Types of RDD Operations: Transformations and Actions
- Transformations (filter, map, union): operations producing a new RDD by manipulation on another RDD
- Transformations are evaluated lazily
- Actions (e.g., count or saveAsTextFile): trigger a computation in order to return a result to the calling program or write it to stable storage
- Once an action is triggered on an RDD, Spark examines the RDD's lineage to build a "graph of operations" to be executed

textFile = sc.textFile("SomeFile.txt")
linesWithSpark = textFile.filter(lambda line: "Spark" in line) # Transformation
linesWithSpark.count() # Action → 74
linesWithSpark.first() # Action → '# Apache Spark'How Spark Executes Operations (Lazy Evaluation)
- Understanding Lazy Evaluation and Execution Graphs
- Transformations — LAZY EVALUATION
- Produces a new RDD by manipulating an existing one
- Does NOT compute immediately — Spark just remembers the instruction
- Builds a logical plan of steps (Lineage) in the background
- Examples:
map()→ Create a new RDDfilter()→ Select data by conditionreduceByKey()→ Aggregate data by key
- Actions — TRIGGER COMPUTATION
- Forces Spark to execute the entire stored lineage graph
- Examines the lineage to build an optimized Graph of Operations
- Returns the final result to the Driver or writes to stable storage
- Examples:
count()→ Calculate total recordscollect()→ Return all data to Drivertake(n)→ Fetch limited results

Lazy evaluation is like writing a shopping list: adding items (transformations) costs nothing. You only actually go to the store (compute) when someone says "go now" (an action). And because you have the whole list first, you can plan the shortest route (optimization).
How Spark Executes Operations (Example)
# 1. Create Base RDD
rdd = spark.sparkContext.parallelize([1, 2, 3, 4], 2)
# → Recorded as a Transformation (Lazy)
# 2. Apply Map
rdd2 = rdd.map(lambda x: x * 2)
# → Recorded as a Transformation (Lazy)
print("After transformation")
# 3. Collect Data
print(rdd2.collect())
# → Action! Triggers Graph Execution- Behind the Scenes:
- When
map()is called, Spark merely records the instruction — no data processing happens yet - The
printstatement executes first, proving Spark bypassed the computation - Only when
collect()is called does Spark build the execution graph and process the data
- When

Transformations
- Transformations: operations producing a new RDD by manipulation on another RDD. Transformations are evaluated lazily
| Function | Description |
|---|---|
map() | Returns a new RDD by applying the function on each data element |
flatmap() | Similar to map(), yet flattens by removing the outermost container |
filter() | Returns a new RDD formed by selecting those elements of the source on which the function returns true |
reduceByKey() | Aggregates the values of a key using a function |
groupByKey() | Converts a (key, value) pair into a (key, <iterable value>) pair |
union() | Returns a new RDD that contains all elements and arguments from the source RDD |
intersection() | Returns a new RDD that contains an intersection of the elements in the datasets |
mapvsflatMapexample:["a b", "c"].map(split)→[["a","b"], ["c"]](list of lists)["a b", "c"].flatMap(split)→["a","b","c"](flattened)
Transformations: Narrow vs Wide
- Narrow Dependency: has a 1-to-1 data dependency
- The data required to compute a new partition lives inside exactly one parent partition
- Examples:
map(),filter(),union()

- Wide Dependency: has an All-to-All dependency
- The data required to compute a single new partition comes from multiple parent partitions scattered across the cluster
- Examples:
join(),groupByKey(),reduceByKey() - Requires a Shuffle → creates a new Stage

Narrow = each student grades their own worksheet (no talking needed). Wide = everyone must swap papers across the whole room so that all "A" answers go to one person, all "B" answers to another — that swapping is the expensive shuffle.
Actions
- Actions: Return the end result of RDD computations. Actions are operations that provide non-RDD values. Some of the common actions used in Spark:
| Function | Description |
|---|---|
count() | Gets the number of data elements in an RDD |
collect() | Gets all the data elements in an RDD as an array |
reduce() | Aggregates data elements into an RDD by taking two arguments and returning one |
take(n) | Fetches the first elements of an RDD |
foreach(operation) | Executes the operation for each data element in an RDD |
first() | Retrieves the first data element of an RDD |
Spark Lineage Graph
- Every Transformation in Spark creates a new RDD that is dependent on its parent RDDs
- This chain of dependencies — keeping track of the "ancestry" of how an RDD was built — is called the Lineage Graph, also referred to as a DAG (Directed Acyclic Graph)
- Helps in fault tolerance
- Query Optimization
# 1. Load data & chain transformations
rdd1 = spark.sparkContext.textFile("server_logs.txt")
rdd2 = rdd1.filter(lambda x: "ERROR" in x)
rdd3 = rdd2.map(lambda x: x.split(" "))
# 2. Print the execution plan (Lineage)
print(rdd3.toDebugString().decode('utf-8'))- Console output:
(2) PythonRDD[3] at RDD at PythonRDD.scala:53 []
| server_logs.txt MapPartitionsRDD[1] at textFile []
| server_logs.txt HadoopRDD[0] at textFile []Lineage is a family tree for data. If a partition is lost, Spark doesn't need a backup copy — it just looks up the family tree and recomputes that piece from its parents.
Spark Lineage Graph (Complete Visual Map)
- Complete visual map of a Spark job: partitions, narrow and wide transformations, and actions
- This entire map is the Lineage Graph — Spark's internal master plan for how to process the data

- Everything left of the dashed line = lazy plan (transformations only recorded)
- Everything right of the dashed line = compute (triggered by the action)
- Note: a co-partitioned join needs no shuffle (data with the same key is already in the matching partition)
Roadmap — Spark Fundamentals (Progress)
Why Apache Spark?Spark Architecture and ExecutionSpark Deployment ModeResilient Distributed Datasets (RDD)Lazy Evaluation, Lineage- Spark using Python (PySpark) ← now
- Running on AWS EMR
Spark on Local Machine: System Prerequisites (The Foundation)
- Install Python: Download and install Python (3.8 or newer)
- Install Java (JDK): JDK 11 or 17; this is recommended for compatibility, https://adoptium.net
- Set Environment Variables (Windows):
JAVA_HOMEpointing to the JDK installation folder (e.g.,C:\Program Files\Java\jdk-11) - Hadoop Error Prevention on Windows: download
winutils.exe, place it in a dedicated folder (e.g.,C:\hadoop\bin), and create aHADOOP_HOMEenvironment variable pointing toC:\hadoop(https://github.com/cdarlint/winutils)

Spark on Local Machine: Visual Studio Code Configuration
- Open VS Code
- Navigate to the Extensions view (the square blocks icon on the left sidebar or
Ctrl+Shift+X) - Search for and install these two essential extensions:
- Python (by Microsoft)
- Jupyter (by Microsoft) — critical for rendering clean, readable DataFrames during data analytics labs
- Create a Workspace: Create an empty folder on the computer (e.g.,
BigData_Lab1) and drag it into VS Code to open the project - Launch Terminal: Go to the top menu and select Terminal > New Terminal (or press
Ctrl+`) - Install PySpark: Execute the following command in the terminal:
pip install pyspark
# Or
python -m pip install pysparkSpark on Local Machine: Writing and Executing the First Spark Job
- Using Jupyter Notebooks (.ipynb) inside VS Code is the best approach to run code block-by-block and inspect intermediate results easily
from pyspark.sql import SparkSession
spark = SparkSession.builder \
.appName("DES431-WordCount") \
.getOrCreate()
sc = spark.sparkContext
lines = sc.parallelize([
"spark is fast", "spark is distributed","big data with spark"
], 4)
# Transformations
words = lines.flatMap(lambda line: line.lower().split())
pairs = words.map(lambda word: (word, 1))
counts = pairs.reduceByKey(lambda a, b: a + b)
# Action
result = counts.collect()
print(sorted(result))- Output:
[('big', 1),
('data', 1),
('distributed', 1),
('fast', 1),
('is', 2),
('spark', 3),
('with', 1)]- Step by step:
flatMap→ split every line into words →["spark", "is", "fast", "spark", ...]map→ turn each word into(word, 1)reduceByKey→ add up the 1s for each word (wide transformation → shuffle)collect→ the action that actually runs everything
Spark using Python (Lambda Expressions)
- With Python, we normally use Lambda expressions
- Lambda is used for creating small, one-time, anonymous function objects in Python
- Syntax:
lambda arguments: expression

- Parts of a lambda:
lambdakeyword — creates the lambda expression- Parameters — one or more parameters are supported; must be separated by a comma (
,) and no parentheses - Colon — this is a cue for the expression
- Expression — must be a single valid Python expression
- These two are equivalent:
lambda a, b: a + bdef add (a, b):
return a + bA lambda is a sticky note function — quick, unnamed, used once, then thrown away. A
deffunction is a labeled recipe card you keep in the drawer.
Word Count Example in Spark (Step by Step)
- Using Python and PySpark with RDD: transformation and action

- RDD input:
w1 w2 w3
w1 w1 w3
w1 w3 w3flatMap(lambda x: x.split(' '))→ Flatten to be one dimension- RDD words:
[w1, w2, w3, w1, w1, w3, w1, w3, w3]
- RDD words:
map(lambda x: (x,1))→ Transform data to array (key-value pairs)- RDD words with initial counts:
[(w1,1), (w2,1), (w3,1), (w1,1), (w1,1), (w3,1), (w1,1), (w3,1), (w3,1)](one(word, 1)pair per word; the slide's list has a small typo with one extra(w1,1))
- RDD words with initial counts:
reduceByKey(lambda x,y: x+y)→ Combine data by key with sum operation- RDD words with final counts:
[(w1,4), (w2,1), (w3,4)]
- RDD words with final counts:
Same idea as MapReduce from Lecture 6:
flatMap+map= the Map phase,reduceByKey= Shuffle + Reduce.
Spark using Python (Workflow)
- Create AWS EMR (Add Spark, Jupyter, Zeppelin)
- Install Python with PySpark Library
- Install Jupyter Notebook (optional)
- Get a Spark session
- Create Dataset (RDD) from data collection (Parallelizing) or load from file (local, HDFS, S3)
- Perform transform operations with lambda functions
- Perform action operations with lambda functions
- Save Output data (local, HDFS, S3)

Word Count Example in Spark Cluster
- Using Python and PySpark with RDD: transformation and action
import pyspark
import sys
if len(sys.argv) != 3:
raise Exception("Exactly 2 arguments are required: <inputUri> <outputUri>")
inputUri=sys.argv[1]
outputUri=sys.argv[2]
sc = pyspark.SparkContext()
lines = sc.textFile(sys.argv[1])
words = lines.flatMap(lambda line: line.split(" "))
wordCounts = words.map(lambda word: (word, 1)).reduceByKey(lambda count1,count2: count1 + count2)
wordCounts.saveAsTextFile(sys.argv[2])- Annotations from the slide:
import pyspark,import sys→ Import libraryinputUri=sys.argv[1],outputUri=sys.argv[2]→ Get parameter for input path and output pathlines = sc.textFile(sys.argv[1])→ Read filewords = lines.flatMap(...)→ Split file with delimiter for each linewordCounts.saveAsTextFile(sys.argv[2])→ Start process and save output (this is the action)
- Note: the
raiseline should be indented under theifin real Python
Run Spark on AWS EMR: Create Cluster
- Clone an existing EMR; make sure to include the following software:
- Hadoop, Tez, Hive, Hue, Pig, Spark, Livy, JupyterHub, Zeppelin
- Wait until status shows "Waiting"

Run Spark on AWS EMR: Interactive Shell
- You can access PySpark via the interactive shell using the command
pyspark - Run
scto check the connection context

[hadoop@ip-...]$ pyspark
...
SparkSession available as 'spark'.
>>> sc
<SparkContext master=yarn appName=PySparkShell>master=yarn→ the shell runs in client mode on YARN
Run Spark on AWS EMR: Word Count from S3
- Run command for word count from file in S3:
>>> lines = sc.textFile("s3://book-5186186/book.txt")
>>> words = lines.flatMap(lambda line: line.split(" "))
>>>
>>> wordCounts = words.map(lambda word: (word, 1)).reduceByKey(lambda count1,count2: count1 + count2)- Show output on screen:
>>> wordCounts.take(10)
[(u'', 7426), (u'resqueness', 1), (u'four', 19), (u'prefix', 1), (u"friend's", 4), (u'LAST', 7), (u'besmear', 1), (u'originality', 1), (u'Smiles./', 1), (u'immature', 1)]- Save output to S3:
>>> wordCounts.saveAsTextFile("s3://book-5186186/wordcount.txt")- Note:
(u'', 7426)→ empty strings come from splitting on single spaces when there are multiple spaces / blank lines
Run Spark on AWS EMR: Check Bucket on S3
- Check bucket on S3

wordcount.txt/is actually a folder, containing:_SUCCESS→ empty marker file meaning the job finishedpart-00000,part-00001→ one output file per partition
Spark writes like a team: each worker (partition) writes its own page (
part-0000x), and the_SUCCESSfile is the "all done" sticky note.
Access Spark Task History
- EMR also provides a Web GUI for each service on Hadoop
- Replace the URL with your EMR URL
- We normally check:
- Yarn ResourceManager (8088)
- Spark HistoryServer (18080)
- JupyterHub (9443)
- Allow new incoming port!!
- On the Security group of the master node

| Name of interface | URI |
|---|---|
| Flink history server (EMR version 5.33 and later) | http://master-public-dns-name:8082/ |
| Ganglia | http://master-public-dns-name/ganglia/ |
| Hadoop HDFS NameNode (EMR version pre-6.x) | https://master-public-dns-name:50470/ |
| Hadoop HDFS NameNode | http://master-public-dns-name:50070/ |
| Hadoop HDFS DataNode | http://coretask-public-dns-name:50075/ |
| Hadoop HDFS NameNode (EMR version 6.x) | https://master-public-dns-name:9870/ |
| Hadoop HDFS DataNode (EMR version pre-6.x) | https://coretask-public-dns-name:50475/ |
| Hadoop HDFS DataNode (EMR version 6.x) | https://coretask-public-dns-name:9865/ |
| HBase | http://master-public-dns-name:16010/ |
| Hue | http://master-public-dns-name:8888/ |
| JupyterHub | https://master-public-dns-name:9443/ |
| Livy | http://master-public-dns-name:8998/ |
| Spark HistoryServer | http://master-public-dns-name:18080/ |
| Tez | http://master-public-dns-name:8080/tez-ui |
| YARN NodeManager | http://coretask-public-dns-name:8042/ |
| YARN ResourceManager | http://master-public-dns-name:8088/ |
| Zeppelin | http://master-public-dns-name:8890/ |
Access Spark Task History: YARN Resource Manager
- Yarn Resource Manager → "All Applications" page

- Shows each Spark application with its State (RUNNING / FINISHED), FinalStatus (UNDEFINED / SUCCEEDED), allocated vCores and memory, and a Tracking UI link
Access Spark Task History: History Server
- History Server (
https://IP:18080)


- Each action became one Job (e.g.,
count,take,saveAsTextFile→SparkHadoopWriter) - "skipped" stages = Spark reused shuffle output from an earlier job instead of recomputing it

- The Executors tab shows the driver and every executor, their cores, memory, completed tasks, input size and shuffle read/write
Write Spark on Jupyter Notebook
- Access to
https://IP:9443 - Default user/pass is
jovyan/jupyter - Create a new notebook with PySpark3


- Initialize Connection — running
scin the first cell starts the Spark application (through Livy)
sclines = sc.textFile("s3://book-5186186/book.txt")words = lines.flatMap(lambda line: line.split(" "))wordCounts = words.map(lambda word: (word, 1)).reduceByKey(lambda count1,count2: count1 + count2)- Spark start execution — only at the action:
wordCounts.take(5)
# [('HAWTHORNE.', 77), ('', 7426), ('I.', 4), ('It', 131), ('necessary,', 1)]Cells 2–4 run instantly because they're lazy transformations; cell 5 (
take) is the action that actually makes the cluster do work.
Useful RDD Transformations: map and flatMap
map(function)andflatmap(function)
data = ["Apple,Amy", "Butter,Bob", "Cheese,Chucky"]
data = sc.parallelize(data)# map
data.map(lambda line: line.split(',')).take(3)
# [['Apple', 'Amy'], ['Butter', 'Bob'], ['Cheese', 'Chucky']]data.map(lambda line: line.lower()).take(3)
# ['apple,amy', 'butter,bob', 'cheese,chucky']# flatMap
data.flatMap(lambda line: line.split(',')).take(6)
# ['Apple', 'Amy', 'Butter', 'Bob', 'Cheese', 'Chucky']map→ one input → exactly one output (a list stays a list)flatMap→ one input → zero or more outputs (the lists are flattened)
Useful RDD Transformations: mapValues and flatMapValues
mapValues(function)andflatMapValues(function)— work only on the value of each(key, value)pair; the key is kept
pair_data = [('Apple', 'Amy'), ('Butter', 'Bob'), ('Cheese', 'Chucky')]
pair_data = sc.parallelize(pair_data)# mapValues()
# each pair: (key, value)
pair_data.mapValues(lambda name: name.lower()).take(3)
# [('Apple', 'amy'), ('Butter', 'bob'), ('Cheese', 'chucky')]# flatMapValues()
pair_data.flatMapValues(lambda name: name.lower()).take(6)
# [('Apple', 'a'),
# ('Apple', 'm'),
# ('Apple', 'y'),
# ('Butter', 'b'),
# ('Butter', 'o'),
# ('Butter', 'b')]- Why letters? A string is iterable, so
flatMapValuessplits"amy"into'a','m','y'and pairs each with the same key
Useful RDD Transformations: filter and groupByKey
filter(function)— keep only elements where the function returnsTrue
# filter
data = sc.parallelize([1, 2, 3, 4, 5])
data.filter(lambda x: x % 2 != 0).take(3)
# [1, 3, 5]groupByKey(): When called on an RDD of(K, V)pairs, returns a new RDD of(K, Iterable<V>)
# groupByKey()
data = sc.parallelize([('A', 1), ('A', 2), ('B', 3), ('C', 4)])
print(data.groupByKey().take(1))
for pair in data.groupByKey().take(1):
print(pair[0], [n for n in pair[1]])[('A', <pyspark.resultiterable.ResultIterable object at 0x7f0b00a85290>)]
('A', [1, 2])- The grouped values are a ResultIterable object → convert to a list to see them
Useful RDD Transformations: reduceByKey and sortBy
reduceByKey(): Combine elements of an RDD by key and then apply a reduce function to pairs of values until only a single value remains
# reduceByKey()
data = sc.parallelize([('A', 1), ('A', 2), ('B', 3), ('C', 4)])
data.reduceByKey(lambda v1, v2: v1 + v2).take(1)
# [('A', 3)]sortBy(): Sort an RDD according to a sorting function and return the results in a new RDD
# sortBy()
data = sc.parallelize([('A', 99), ('B', 3), ('C', 4)])
print(data.sortBy(lambda pair: pair[1]).take(4))
print(data.sortBy(lambda pair: -pair[1]).take(4))
print(data.sortBy(lambda pair: pair[0]).take(4))[('B', 3), ('C', 4), ('A', 99)]
[('A', 99), ('C', 4), ('B', 3)]
[('A', 99), ('B', 3), ('C', 4)]pair[1]→ sort by value ascending;-pair[1]→ sort by value descending;pair[0]→ sort by key
groupByKeyvsreduceByKey:groupByKeyships every value across the network then groups;reduceByKeyadds things up locally first (like a combiner in MapReduce), so it shuffles much less data. PreferreduceByKeyfor sums/counts.
Useful RDD Actions: take, top, count, foreach
take,top,count
wordCounts.take(5)
# [('HAWTHORNE.', 77), ('', 7426), ('I.', 4), ('It', 131), ('necessary,', 1)]wordCounts.count()
# 12756wordCounts.top(5)
# [(... strange non-ASCII "words" ..., 1), ...]
top(n)returns the largest elements by natural ordering (here the tuples are compared by the word string, so odd symbols sort last and appear "on top")foreach: applies a function to each element of the RDD on the executors and returns no result to the driver
acc = sc.accumulator(0)
def add_to_accumulator(x):
global acc
acc += x[1]
wordCounts.foreach(add_to_accumulator)
print(acc)
# 69961- An accumulator is a shared variable that executors can only add to; the driver reads the final value
- Here it sums all counts → total number of tokens:
foreachis like asking every worker to drop coins into one shared piggy bank (the accumulator) — they don't hand anything back to you individually, you just check the piggy bank at the end.
Summary
- Why Apache Spark? → in-memory, reusable, fault-tolerant, unified engine (vs disk-based Hive/MapReduce)
- Spark Architecture and Execution → Driver (SparkContext) → DAG Scheduler → Stages → Tasks → Executors on worker nodes
- Spark Deployment Mode → Local, Client (interactive/Jupyter), Cluster (production)
- Resilient Distributed Datasets (RDD) → immutable, partitioned, lazy, lineage-aware
- Transformations → lazy, return a new RDD (narrow vs wide)
- Actions → trigger execution, return a non-RDD value
- Lazy Evaluation, Lineage → build a DAG first, compute only on action; lineage gives fault tolerance
- Spark using Python (PySpark) → lambda functions,
flatMap/map/reduceByKey - Running on AWS EMR →
pysparkshell, S3 input/output, YARN (8088), History Server (18080), JupyterHub (9443)