HW4 - MapReduce on EMR
Overview
- Homework Assignment 4 (1/2026) — 5 Marks
- DES431 Big Data Analytics and Machine Learning — ICT, SIIT
- Instructor: Dr. Apichon Witayangkurn
- Goal: learn how to develop a MapReduce program and run Hadoop in an AWS environment (Amazon EMR)
- You must complete all the tasks (check the tutorial document) and capture screenshots after each step (see the Lecture 7 document)
Related
- Lecture 7 - Practice MapReduce with EMR — the step-by-step tutorial this homework follows
- Lecture 6 - MapReduce Framework and Programming — Mapper / Reducer / Driver theory
Assignment Tasks
1. Screen Capture of Tutorial Part
| # | Screenshot | Where in Lecture 7 |
|---|---|---|
| 1.1 | AWS EMR: Ready to use | Cluster summary with status Waiting + Primary node public DNS |
| 1.2 | Test Web Access for HDFS GUI | http://<primary-dns>:9870 |
| 1.3 | Test Web Access for YARN GUI | http://<primary-dns>:8088 |
| 1.4 | Ready to Run MapReduce | SSH into primary node, EMR logo + prompt |
| 1.5 | Execute MapReduce job | hadoop jar ... WordCountDriver /wordcount /wordcount_output |
| 1.6 | Check Result from CLI | hadoop fs -ls + hadoop fs -cat .../part-r-00000 |
| 1.7 | Check Result file on HDFS | HDFS UI → Utilities → Browse the file system (URL visible) |
| 1.8 | Check MapReduce process on YARN | YARN UI → application WordCounter |
2. Exercise
- Create a MapReduce program to list unique ID with total line count of each ID, using
taxi.csv
| # | Screenshot |
|---|---|
| 2.1 | Execute MapReduce job |
| 2.2 | Check Result from CLI |
| 2.3 | Check MapReduce process on YARN |
- Submit via Google Classroom Assignment
Setup Used in the Solution
- Cluster: Amazon EMR
emr-7.9.0with Hadoop 3.4.1, Hive, Hue, JupyterHub, Livy, Pig, Spark, Tez, Zeppelin- 1 Primary + 2 Core nodes
- IDE: IntelliJ IDEA + Maven (instead of Eclipse + manually copied
lib/jars from the slides)- Hadoop libraries come from the
hadoop-client3.4.1 Maven dependency (scopeprovided) mvn clean packagebuildsMRWordCount.jar
- Hadoop libraries come from the
- Package name =
s+ your student ID (the slides say "define package as your student id"; Java package names can't start with a digit, so prefix withs)- In the code below the ID is replaced with
sXXXXXXXXXX→ change it to your own
- In the code below the ID is replaced with
- Data files (from
MRTutorialData/data/):book.txt— a book (~7,426 lines, ~364 KB) → input for WordCounttaxi.csv— taxi GPS records (~255,000 lines, no header) → input for the Exercise
- Files were uploaded to the primary node with
scp, and accessed over SSH as userhadoop
Maven vs. copying jars by hand: copying
hadoop-common.jarintolib/is like photocopying a recipe book page by page; Maven is like telling the librarian "I need Hadoop 3.4.1" and it fetches the exact right books for you automatically.
Project Structure
HW4-MapReduce/
├── pom.xml
└── src/main/java/sXXXXXXXXXX/
├── WordCountMapper.java ← tutorial (1.x)
├── WordCountReducer.java ← tutorial (1.x), REUSED by the exercise
├── WordCountDriver.java ← tutorial (1.x)
├── TaxiMapper.java ← exercise (2.x) — NEW
└── TaxiDriver.java ← exercise (2.x) — NEW- One jar (
MRWordCount.jar) contains both programs → choose which to run by the main class name in thehadoop jarcommand

pom.xml (Maven Build File)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>HW4-MapReduce</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>3.4.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>MRWordCount</finalName>
</build>
</project>- Explanation:
maven.compiler.source/target = 8→ compile to Java 8 bytecode (same idea as "compiler compliance level 1.8" in Eclipse) so it runs on the cluster's JVMhadoop-client3.4.1 → matches the cluster's Hadoop 3.4.1 (fromemr-7.9.0)<scope>provided</scope>→ needed to compile, but not packed into the jar — the EMR cluster already provides Hadoop at runtime → jar stays tiny<finalName>MRWordCount</finalName>→ output file istarget/MRWordCount.jar(same name as the tutorial)
- Build:
mvn clean package
# → target/MRWordCount.jarPart 1 — Tutorial: WordCount
WordCountMapper.java
package sXXXXXXXXXX;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
@Override
public void map(LongWritable key, Text value, Context con) throws IOException, InterruptedException {
String line = value.toString(); // Get all lines from the input files
String[] words = line.split(" "); // Extract all the words
for (String word : words) {
Text outputKey = new Text(word.toUpperCase().trim());
IntWritable outputValue = new IntWritable(1);
con.write(outputKey, outputValue);
}
}
}- Input: — Hadoop's default
TextInputFormatgives one line permap()call - Process:
line.split(" ")— cut the line at each spacetoUpperCase().trim()— normalize soThe/the/THE→THE
- Output: one pair per word
- Same logic as the lecture code (only formatting +
@Overrideadded)
WordCountReducer.java
package sXXXXXXXXXX;
import java.io.IOException;
import java.util.Iterator;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
@Override
protected void reduce(Text key, Iterable<IntWritable> values, Context c) throws IOException, InterruptedException {
int sumOfValues = 0;
Iterator<IntWritable> valuesIt = values.iterator();
// Aggregate the values
while (valuesIt.hasNext()) {
sumOfValues = sumOfValues + valuesIt.next().get();
}
c.write(key, new IntWritable(sumOfValues));
}
}- Input: — after shuffle & sort, all values of the same key arrive together
- Process: loop through the iterator and add them up
- Output:
- ⭐ Generic: it doesn't care if the key is a word or a taxi ID — it just sums numbers per key → that's why the exercise reuses it
WordCountDriver.java
package sXXXXXXXXXX;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
public class WordCountDriver {
public static void main(String[] args) throws Exception {
// Configure Job
Job job = Job.getInstance(new Configuration());
job.setJobName("WordCounter");
job.setJarByClass(WordCountDriver.class);
// Configure Mapper and Reducer class
job.setMapperClass(WordCountMapper.class);
job.setReducerClass(WordCountReducer.class);
// Setting the expected types of output
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setOutputFormatClass(TextOutputFormat.class);
// Configure Input and Output directories
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
// Start the job
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}- Job name
WordCounter→ what shows in the YARN UI (screenshot 1.8) args[0]= HDFS input dir (/wordcount),args[1]= HDFS output dir (/wordcount_output)
Run Commands (1.4 – 1.8)
# On your Mac
chmod 400 labsuser.pem
scp -i labsuser.pem target/MRWordCount.jar book.txt hadoop@<primary-dns>:/home/hadoop/
ssh -i labsuser.pem hadoop@<primary-dns> # 1.4 Ready to Run MapReduce
# On the primary node
hadoop fs -mkdir /wordcount
hadoop fs -put /home/hadoop/book.txt /wordcount
hadoop fs -ls /wordcount
hadoop jar MRWordCount.jar sXXXXXXXXXX.WordCountDriver /wordcount /wordcount_output # 1.5
hadoop fs -ls /wordcount_output # 1.6
hadoop fs -cat /wordcount_output/part-r-00000 # 1.6- 1.7 →
http://<primary-dns>:9870→ Utilities → Browse the file system →/wordcount_output - 1.8 →
http://<primary-dns>:8088→ application WordCounter, state FINISHED / SUCCEEDED
Results & Observations (WordCount)
- Job reached
map 100% reduce 100%and completed successfully - 1 input split → 1 map task; 3 reduce tasks → 3 output files
part-r-00000…part-r-00002(~40.6–40.9 KB each) +_SUCCESS - Mapper read 7,426 lines and emitted 63,640 pairs → reducers grouped them into 12,127 distinct words
- Punctuation stays attached (e.g.
"Iand(Iare counted separately fromI) because the mapper only splits on a space- Fix idea: strip punctuation in the mapper, e.g.
word.replaceAll("[^A-Za-z']", ""), and skip empty strings
- Fix idea: strip punctuation in the mapper, e.g.
- HDFS UI uses port 9870 in Hadoop 3 (Hadoop 2 used 50070 — the old slide screenshot shows 50070)


Part 2 — Exercise: Count Records per Taxi ID
The Idea
- Task: list every unique taxi ID and how many lines (records) it has in
taxi.csv - This is exactly the WordCount pattern with a different key:
| WordCount | Taxi Count | |
|---|---|---|
| Input line | It was the best of times | 5yc/f14Tqe9XCRu5qCGxv5qo+ug,1,13.83610,... |
| Split by | space " " | comma "," |
| Key emitted | every word | column 0 only (the ID) |
| Value emitted | 1 | 1 |
| Reducer | sum | same sum (reuse WordCountReducer) |
| Emits per line | many pairs | exactly 1 pair |
- So only 2 new classes are needed:
TaxiMapperandTaxiDriver
Imagine a toll booth log with one row every time a taxi passes. To know how many times each taxi passed, you don't need to read the whole row — you only look at the license plate (first column), make a tally mark next to it, then count the tally marks per plate.
TaxiMapper.java (NEW)
package sXXXXXXXXXX;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class TaxiMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
// Column index of the ID in taxi.csv (0 = first column). Change after checking head -3 taxi.csv
private static final int ID_COLUMN = 0;
private final Text outputKey = new Text();
private final IntWritable one = new IntWritable(1);
@Override
public void map(LongWritable key, Text value, Context con) throws IOException, InterruptedException {
String line = value.toString().trim();
if (line.isEmpty()) {
return;
}
String[] fields = line.split(",");
if (fields.length <= ID_COLUMN) {
return;
}
String id = fields[ID_COLUMN].trim();
if (id.isEmpty()) {
return;
}
outputKey.set(id);
con.write(outputKey, one);
}
}- Walkthrough:
ID_COLUMN = 0— the taxi ID is the first column (checked withhead -3 taxi.csv); kept as a constant so it's easy to changeoutputKey/oneas fields — create theTextandIntWritableobjects once and reuse them (outputKey.set(id)) instead ofnewon every line → less garbage for 255,000 lines- Safe because
con.write()serializes the pair immediately
- Safe because
trim()+isEmpty()→ skip blank lines (e.g. trailing newline at end of file)split(",")→ CSV columnsfields.length <= ID_COLUMN→ guard against malformed lines (avoidsArrayIndexOutOfBoundsException)id.isEmpty()→ skip rows with a missing IDcon.write(outputKey, one)→ emit — exactly one pair per valid line
- Case is kept as-is (no
toUpperCase()) — IDs like5yc/f14T...are case-sensitive (base64-like), so upper-casing could merge different taxis- Note: the sample result on the slide shows upper-case IDs, which suggests the instructor reused the WordCount mapper's
toUpperCase(); keeping the original case is the more correct choice
- Note: the sample result on the slide shows upper-case IDs, which suggests the instructor reused the WordCount mapper's
The three
returnchecks are like a bouncer at the door: empty line? out. Not enough columns? out. No ID? out. Only clean rows get counted.
TaxiDriver.java (NEW)
package sXXXXXXXXXX;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
public class TaxiDriver {
public static void main(String[] args) throws Exception {
Job job = Job.getInstance(new Configuration());
job.setJobName("TaxiCounter");
job.setJarByClass(TaxiDriver.class);
job.setMapperClass(TaxiMapper.class);
job.setReducerClass(WordCountReducer.class); // same sum logic
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setOutputFormatClass(TextOutputFormat.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}- Differences from
WordCountDriver:- Job name
TaxiCounter→ easy to find in the YARN UI (screenshot 2.3) - Mapper =
TaxiMapper - Reducer =
WordCountReducer(reused — same sum logic)
- Job name
- Everything else (output types
Text/IntWritable,TextOutputFormat,args[0]/args[1]) is identical
Run Commands (2.1 – 2.3)
# On your Mac: rebuild and upload the jar + data
mvn clean package
scp -i labsuser.pem target/MRWordCount.jar taxi.csv hadoop@<primary-dns>:/home/hadoop/
# On the primary node
hadoop fs -mkdir /taxi
hadoop fs -put /home/hadoop/taxi.csv /taxi
hadoop fs -ls /taxi
hadoop jar MRWordCount.jar sXXXXXXXXXX.TaxiDriver /taxi /taxi_output # 2.1
hadoop fs -ls /taxi_output # 2.2
hadoop fs -cat /taxi_output/part-r-00000 # 2.2- 2.3 →
http://<primary-dns>:8088→ application TaxiCounter (and the earlier WordCounter), both FINISHED / SUCCEEDED - ⚠️ If you re-run, delete the old output first:
hadoop fs -rm -r /taxi_output
Results & Observations (Taxi)
- Mapper read 255,000 records → emitted 255,000 pairs (one per line)
- Reducers received 4,471 groups → 4,471 distinct taxi IDs
- Average records per taxi:
- Output format matches the sample result:
TAXI_ID<TAB>count, e.g.++DSqYQ5x328LHUqejEnMt1Ari0 47 - Most taxis have ~47–48 records; some have roughly double (~90–98) → probably recorded over a longer period or at a higher sampling rate



Data Flow Summary (Exercise)
taxi.csv (HDFS: /taxi)
│ TextInputFormat: 1 line → 1 map() call
▼
TaxiMapper "5yc/f14T...,1,13.83,100.47,..." → ("5yc/f14T...", 1)
│
▼ Shuffle & Sort (group by taxi ID)
("5yc/f14T...", [1,1,1,...,1])
│
▼
WordCountReducer sum → ("5yc/f14T...", 47)
│
▼
/taxi_output/part-r-0000N (TextOutputFormat: ID<TAB>count)Common Pitfalls
- Output directory already exists → job fails (
FileAlreadyExistsException) →hadoop fs -rm -r <output> - Wrong main class →
ClassNotFoundException→ use the full namepackage.ClassName(e.g.sXXXXXXXXXX.TaxiDriver) - Can't open 9870 / 8088 / SSH → add inbound rules for your current public IP (
/32) on the primary node's security group; your IP changes when you switch networks Permissions 0644 for 'labsuser.pem' are too open→chmod 400 labsuser.pem- Version mismatch → compile for Java 8 and use the same Hadoop version as the cluster (3.4.1), with
providedscope - Cluster gone next session → EMR stops with the lab / after 3 h idle → use Clone to recreate it with the same settings