HW6 - Work with Spark
Overview
- Homework Assignment 6 (1/2026) — 5 Marks
- DES431 Big Data Analytics and Machine Learning, ICT, SIIT — Instructor: Dr. Apichon Witayangkurn
- Goal: use Spark to process data on Amazon EMR
- You must complete all the tasks (check the tutorial document) and capture screenshots after each step (slides marked CAPTURE SCREEN)
- Input files:
book.txt(~356 KB text) andtaxi_header.csv(~19.4 MB taxi GPS data) — from the assignment in Google Classroom - Spark is used in four ways:
- Interactive
pysparkshell (RDD word count) - Jupyter notebook (RDD, DataFrame and Spark SQL)
- A user-defined function (UDF)
- Structured Streaming with
spark-submit
- Interactive
Your Tasks
- Prepare EMR with Spark (Add Spark, Jupyter, Zeppelin)
- Config file location for Jupyter notebook in S3
- Prepare data on S3
- Run WordCount on Spark Shell
- Check Spark Task History
- Write Spark on Jupyter notebook
- Use PySpark DataFrame to process data
- Use Spark SQL to process data
- Create User-defined function
- Create WordCount Stream version
- You will create only one Python file:
wordStream.py, and the command to run isspark-submit wordStream.py
- You will create only one Python file:
1. Prepare EMR with Spark
- Clone an existing EMR with the modules in the figure (see check boxes)
- Hadoop, Hive, Hue, JupyterHub, Livy, Pig, Spark, Tez, Zeppelin
- Release used:
emr-7.9.0(Hadoop 3.4.1, Hive 3.1.3, Hue 4.11.0, JupyterHub 1.5.0, Livy 0.8.0, Pig 0.17.0, Spark 3.5.5, Tez 0.10.2, Zeppelin 0.11.1) - Capacity: 1 Primary | 2 Core | 0 Task
- Wait until status shows "Waiting" → EMR is ready to use — CAPTURE SCREEN
- Use the Primary node public DNS for remote connection (SSH, web UIs)

- What I did: cloned the cluster from the previous homework (already had all apps installed) and waited for Waiting

Cloning the cluster is like "Save As" on a document — you get the same setup without ticking every box again.
2. Config File Location for Jupyter Notebook in S3
- Go to S3 and create a bucket named
myjupyterbackupsXXXXX(name must be unique)- Region: US East (N. Virginia) us-east-1; keep Block all public access on
- In EMR, go to Configurations → Instance group configurations
- Select Instance group Primary → Reconfigure → Edit in JSON → add the configuration below (change to your bucket):
[ { "Classification": "jupyter-s3-conf",
"Properties": { "s3.persistence.bucket": "myjupyterbackupsXXXXX",
"s3.persistence.enabled": "true" } } ]- Verify setting — the Primary instance group now shows two
jupyter-s3-confrows (s3.persistence.bucket,s3.persistence.enabled = true) with status Running — CAPTURE SCREEN


- Why? By default JupyterHub saves notebooks on the primary node's local disk → they are lost when the cluster terminates. This setting makes JupyterHub save notebooks to S3 instead
It's like turning on iCloud sync for your notes: if the laptop (cluster) is thrown away, the notes are still in the cloud (S3).
3. Prepare Data on S3
- Go to S3 and create a bucket named
book-your_student_id - Upload files:
book.txtandtaxi_header.csv— CAPTURE SCREEN


4. Run WordCount on Spark Shell
-
SSH to the primary node, then start the interactive shell with
pyspark -
Run
scto check the connection context →<SparkContext master=yarn appName=PySparkShell> -
Run the word count from the file in S3 (change bucket name to your bucket), show output on screen, and save output to S3
-
My code (bucket name replaced with a placeholder):
lines = sc.textFile("s3://book-<student_id>/book.txt")
words = lines.flatMap(lambda line: line.split(" "))
wordCounts = words.map(lambda word: (word, 1)).reduceByKey(lambda count1,count2: count1 + count2)
wordCounts.take(10)
wordCounts.saveAsTextFile("s3://book-<student_id>/wordcount.txt")- Line by line:
textFile→ read the book from S3 as an RDD of linesflatMap(... split(" "))→ split each line into words (flattened)map(lambda word: (word, 1))→ pair each word with 1reduceByKey(...)→ sum the counts per wordtake(10)→ action: show 10 resultssaveAsTextFile(...)→ action: write the full result to S3
- Check the bucket on S3:
wordcount.txt/is a folder with_SUCCESS,part-00000,part-00001— CAPTURE SCREEN



- Observations:
- The transformations (
textFile,flatMap,map,reduceByKey) return immediately → Spark is lazy; work only starts at the actionstakeandsaveAsTextFile - Output is a folder, with one
partfile per partition (2 here) - The empty string has the highest count (7,426) because splitting a blank line by a space gives an empty word → blank lines should be filtered out for a cleaner result
- Words keep their punctuation (e.g.,
HAWTHORNE.)
- The transformations (
5. Check Spark Task History
- EMR 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
- I allowed ports 22, 8088, 18080, 9443 from my IP only
- History Server (
https://IP:18080) → list of applications → open one to see its Jobs — CAPTURE SCREEN



- Observations:
- After leaving the shell, the History Server lists
PySparkShellas completed (about 2.3 minutes) - Two actions → two jobs (job 0 =
take, job 1 =saveAsTextFile) - Job 1 shows "1/1 (1 skipped)" stages → the shuffle output of the
mapstage was already computed by job 0, so Spark reused it instead of reading the book again
- After leaving the shell, the History Server lists
"Skipped" stage = leftovers in the fridge. Spark already cooked that part for the first job, so the second job just reheats it.
6. Write Spark on Jupyter Notebook
- Access
https://IP:9443(JupyterHub) - Sign in with the default JupyterHub user
jovyan(default password is given in the tutorial) - Create a new notebook with PySpark3
- On my EMR release it is listed as "PySpark" instead of "PySpark3" (it runs Python 3)
- Run
scfirst → Initialize Connection (starts a Spark application through Livy) - Run the same word count → Spark start execution at the action — CAPTURE SCREEN
sclines = sc.textFile("s3://book-<student_id>/book.txt")words = lines.flatMap(lambda line: line.split(" "))wordCounts = words.map(lambda word: (word, 1)).reduceByKey(lambda count1,count2: count1 + count2)wordCounts.take(5)
# [('HAWTHORNE.', 77), ('', 7426), ('I.', 4), ('It', 131), ('necessary,', 1)]


7. Use PySpark DataFrame to Process Data
-
Load file from S3 to a Spark DataFrame (change bucket name to your prepared bucket), with header and schema inference
-
Remember Homework? (MapReduce in HW4) → Count points for each VehicleID — CAPTURE SCREEN
-
Write the result to S3 normally, and again as one file using
coalesce(1) -
Check output in S3 under your bucket for the single file — CAPTURE SCREEN
-
My code:
df2=spark.read.format('csv').options(header='true', inferSchema='true').load("s3://book-<student_id>/taxi_header.csv")
df2.show()
df2.printSchema()
df3 = df2.groupBy("VehicleID").count()
df3.show()
df3.write.csv("s3://book-<student_id>/VehicleID.csv")
df3.coalesce(1).write.csv("s3://book-<student_id>/VehicleIDSingle.csv")- Explanation:
header='true'→ first row is the column namesinferSchema='true'→ Spark guesses column types- Columns:
VehicleID | gpsvalid | lat | lon | timestamp | speed | heading | for_hire_light | engine_acc groupBy("VehicleID").count()→ number of GPS records per taxi (same as the HW4 MapReduce job, in one line)write.csv(...)→ output folder with many part files (one per partition)coalesce(1)→ merge into one partition → one CSV file (part-00000-….csv+_SUCCESS)



- Observations:
- Schema inference detects
timestampas timestamp,lat/lonas double, other numeric columns as integer - Matches the MapReduce exercise in Homework 4: 255,000 records from 4,471 taxis, mostly 46–48 records per taxi and some about double (up to 98)
coalesce(1)is easier to download, but means one task writes all the data (no parallelism for the write)
- Schema inference detects
coalesce(1)is like asking one person to staple everyone's pages into a single booklet — neat result, but only one person is working.
8. Use Spark SQL to Process Data
- Using SQL queries: create a view with the
createOrReplaceTempViewbuilt-in method and run the SQL query with thespark.sqlmethod - Tutorial code:
#Load the DataFrame API session into Spark and create a session
from pyspark.sql import SparkSession
spark = SparkSession.builder.getOrCreate()
df2.createOrReplaceTempView('taxi_tb')
df3=spark.sql('SELECT VehicleId, count(*) as total FROM taxi_tb group by VehicleId ORDER BY total desc')
df3.show()
spark.sql('SELECT hour(timestamp) as hh, \
min(speed) as min_speed, avg(speed) as avg_speed, max(speed) as max_speed \
FROM taxi_tb where speed >0 \
group by hour(timestamp) order by hh asc').show()- My code:
df2.createOrReplaceTempView('taxi_tb')
df3=spark.sql('SELECT VehicleId, count(*) as total FROM taxi_tb group by VehicleId ORDER BY total desc')
df3.show()
spark.sql('SELECT hour(timestamp) as hh, \
min(speed) as min_speed, avg(speed) as avg_speed, max(speed) as max_speed \
FROM taxi_tb where speed >0 \
group by hour(timestamp) order by hh asc').show()- Two queries:
- Find total data points by taxi →
count(*)grouped byVehicleId, sorted descending - Find min, avg, max speed by hour →
hour(timestamp)as the group, only moving points (speed > 0) — CAPTURE SCREEN
- Find total data points by taxi →
- Tutorial's expected speed-by-hour output:
| hh | min_speed | avg_speed | max_speed |
|---|---|---|---|
| 0 | 1 | 44.177082493347314 | 133 |
| 1 | 1 | 44.406729066531746 | 139 |
| 2 | 1 | 45.216610004856726 | 132 |
| 11 | 1 | 1.0 | 1 |
| 13 | 2 | 2.5 | 3 |
| 22 | 1 | 1.0 | 1 |
| 23 | 1 | 40.43624161073826 | 115 |


- Observations:
- 50 taxis share the maximum of 98 points
- Almost all records (over 99%) are from 23:00–02:59 around midnight of 1 August 2018 → the speed table mainly has hours 23, 0, 1, 2 (average speed 40–45 km/h, max 115–139 km/h)
- Hours 11, 13, 22 come from only four moving records, three of them with old timestamps from other days (April–July 2018) → same kind of data-quality issue seen in Homework 5
A temp view is like giving your DataFrame a nickname so you can talk to it in SQL — the data doesn't move or get copied.
9. Create User-Defined Function
-
Create a function "masker" to mask some characters
- Replaces the first four characters of a string with
#
- Replaces the first four characters of a string with
-
Wrap it as a UDF and register it with
spark.udf.registerso it can be called from SQL — CAPTURE SCREEN -
My code (same as the tutorial):
from pyspark.sql.functions import *
from pyspark.sql.types import *
def masker(var1):
return var1[4:].rjust(len(var1),"#")
maskUDF = udf(lambda z: masker(z),StringType()) # Converting function to UDF
spark.udf.register("masker", masker,StringType())
spark.sql("select masker(VehicleId) as MaskName, timestamp from taxi_tb").show()- How
maskerworks:var1[4:]→ drop the first 4 characters.rjust(len(var1), "#")→ pad on the left with#back to the original length- Example:
"5yc/f14Tqe9X..."→"####f14Tqe9X..."
- Two ways to use it:
maskUDF→ for the DataFrame API (e.g.,df2.select(maskUDF(col("VehicleID"))))spark.udf.register("masker", ...)→ for SQL queries (masker(VehicleId))


A UDF is your own custom stamp: Spark's built-in functions are the standard stamps, and when none fits you carve your own and hand it to every worker.
10. Create WordCount Stream Version
- We will use Spark SQL (Structured Streaming) to create a word count program with stream support
- Create
wordStream.py, save and upload to the master node - My code —
wordStream.py:
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
# Initialize Connection
spark = SparkSession.builder.appName("StructuredNetworkWordCount").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
# Create DataFrame representing the stream of input lines from connection to localhost:9999
lines = spark.readStream.format("socket").option("host", "localhost").option("port", 9999).load()
# Split the lines into words
words = lines.select(explode(split(lines.value, " ")).alias("word"))
# Generate running word count
wordCounts = words.groupBy("word").count()
# Start running the query that prints the running counts to the console
query = wordCounts.writeStream.outputMode("complete").format("console").start()
query.awaitTermination()- Explanation:
readStream.format("socket")onlocalhost:9999→ an unbounded DataFrame; each new line typed becomes a new row in columnvaluesplit(lines.value, " ")→ array of words;explode→ one row per word (the DataFrame version offlatMap)groupBy("word").count()→ running word count (state kept across batches)outputMode("complete")→ print the whole result table after every micro-batchformat("console")→ print to the terminalawaitTermination()→ keep running until stopped (Ctrl+C)setLogLevel("ERROR")→ hide INFO logs so the batch tables are readable
- Run it with two terminals (both SSH'd into the master node):
- Terminal 1 — send words with a socket:
nc -lk 9999(-llisten,-kkeep listening after a client disconnects) - Terminal 2 — run Spark:
spark-submit wordStream.py
- Terminal 1 — send words with a socket:
# Terminal 1
nc -lk 9999
# Terminal 2
spark-submit wordStream.py- Type words into the
ncterminal → each line becomes a new batch in the Spark terminal — CAPTURE SCREEN- I typed
test test test, thenhi ok hi
- I typed
Batch: 0
+----+-----+
|word|count|
+----+-----+
+----+-----+
Batch: 1
+----+-----+
|word|count|
+----+-----+
|test| 3|
+----+-----+
Batch: 2
+----+-----+
|word|count|
+----+-----+
| ok| 1|
| hi| 2|
|test| 3|
+----+-----+



- Observations:
- Because the output mode is
complete, each batch prints the whole running table →testis still 3 in Batch 2 even though it wasn't typed again - Batch 0 is the empty first micro-batch that runs when the query starts
- Because the output mode is
ncis a walkie-talkie you speak into; Spark Streaming is the listener writing a tally on a whiteboard. In "complete" mode it re-reads the whole whiteboard aloud after every new message.
Summary
| Task | Tool | Key idea |
|---|---|---|
| 1–3 | EMR + S3 | Cluster with Spark/Jupyter, notebooks persisted to S3, input data in S3 |
| 4 | pyspark shell | RDD word count; lazy transformations, actions trigger jobs |
| 5 | History Server :18080 | 1 action = 1 job; skipped stages = reused shuffle output |
| 6 | JupyterHub :9443 | Same RDD code via Livy in a notebook |
| 7 | DataFrame API | read.csv + groupBy().count(); coalesce(1) → one output file |
| 8 | Spark SQL | createOrReplaceTempView + spark.sql |
| 9 | UDF | udf(...) for DataFrame API, spark.udf.register for SQL |
| 10 | Structured Streaming | socket source + explode/split + groupBy().count(), complete mode |