HW4 - MapReduce on EMR

Updated 12 Nov 2026

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


Assignment Tasks

1. Screen Capture of Tutorial Part

#ScreenshotWhere in Lecture 7
1.1AWS EMR: Ready to useCluster summary with status Waiting + Primary node public DNS
1.2Test Web Access for HDFS GUIhttp://<primary-dns>:9870
1.3Test Web Access for YARN GUIhttp://<primary-dns>:8088
1.4Ready to Run MapReduceSSH into primary node, EMR logo + prompt
1.5Execute MapReduce jobhadoop jar ... WordCountDriver /wordcount /wordcount_output
1.6Check Result from CLIhadoop fs -ls + hadoop fs -cat .../part-r-00000
1.7Check Result file on HDFSHDFS UI → Utilities → Browse the file system (URL visible)
1.8Check MapReduce process on YARNYARN 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.1Execute MapReduce job
2.2Check Result from CLI
2.3Check MapReduce process on YARN
  • Submit via Google Classroom Assignment

Setup Used in the Solution

  • Cluster: Amazon EMR emr-7.9.0 with 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-client 3.4.1 Maven dependency (scope provided)
    • mvn clean package builds MRWordCount.jar
  • 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 with s)
    • In the code below the ID is replaced with sXXXXXXXXXX → change it to your own
  • Data files (from MRTutorialData/data/):
    • book.txt — a book (~7,426 lines, ~364 KB) → input for WordCount
    • taxi.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 user hadoop

Maven vs. copying jars by hand: copying hadoop-common.jar into lib/ 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 the hadoop jar command


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 JVM
    • hadoop-client 3.4.1 → matches the cluster's Hadoop 3.4.1 (from emr-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 is target/MRWordCount.jar (same name as the tutorial)
  • Build:
mvn clean package
# → target/MRWordCount.jar

Part 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: ⟨byte offset,line⟩\langle \text{byte offset}, \text{line} \rangle — Hadoop's default TextInputFormat gives one line per map() call
  • Process:
    • line.split(" ") — cut the line at each space
    • toUpperCase().trim() — normalize so The / the / THE → THE
  • Output: one ⟨WORD,1⟩\langle \text{WORD}, 1 \rangle pair per word
  • Same logic as the lecture code (only formatting + @Override added)

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: ⟨key,list(1,1,…,1)⟩\langle key, list(1, 1, \dots, 1) \rangle — after shuffle & sort, all values of the same key arrive together
  • Process: loop through the iterator and add them up
  • Output: ⟨key,total⟩\langle key, \text{total} \rangle
  • ⭐ 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
output(k)=∑v∈values(k)v\boxed{\text{output}(k) = \sum_{v \in values(k)} v}

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 ⟨word,1⟩\langle word, 1 \rangle pairs → reducers grouped them into 12,127 distinct words
  • Punctuation stays attached (e.g. "I and (I are counted separately from I) 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
  • HDFS UI uses port 9870 in Hadoop 3 (Hadoop 2 used 50070 — the old slide screenshot shows 50070)
#map tasks=#input splits#output files=#reduce tasks\boxed{\#\text{map tasks} = \#\text{input splits}} \qquad \boxed{\#\text{output files} = \#\text{reduce tasks}}


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:
WordCountTaxi Count
Input lineIt was the best of times5yc/f14Tqe9XCRu5qCGxv5qo+ug,1,13.83610,...
Split byspace " "comma ","
Key emittedevery wordcolumn 0 only (the ID)
Value emitted11
Reducersumsame sum (reuse WordCountReducer)
Emits per linemany pairsexactly 1 pair
  • So only 2 new classes are needed: TaxiMapper and TaxiDriver
map:⟨offset, line⟩→⟨fields[0], 1⟩reduce:⟨id, list(1,…,1)⟩→⟨id, count⟩\boxed{\text{map}: \langle offset,\ line \rangle \rightarrow \langle \text{fields}[0],\ 1 \rangle} \qquad \boxed{\text{reduce}: \langle id,\ list(1,\dots,1) \rangle \rightarrow \langle id,\ \text{count} \rangle}

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 with head -3 taxi.csv); kept as a constant so it's easy to change
    • outputKey / one as fields — create the Text and IntWritable objects once and reuse them (outputKey.set(id)) instead of new on every line → less garbage for 255,000 lines
      • Safe because con.write() serializes the pair immediately
    • trim() + isEmpty() → skip blank lines (e.g. trailing newline at end of file)
    • split(",") → CSV columns
    • fields.length <= ID_COLUMN → guard against malformed lines (avoids ArrayIndexOutOfBoundsException)
    • id.isEmpty() → skip rows with a missing ID
    • con.write(outputKey, one) → emit ⟨id,1⟩\langle id, 1 \rangle — exactly one pair per valid line
  • Case is kept as-is (no toUpperCase()) — IDs like 5yc/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

The three return checks 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)
  • 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 ⟨id,1⟩\langle id, 1 \rangle pairs (one per line)
  • Reducers received 4,471 groups → 4,471 distinct taxi IDs
  • Average records per taxi:
255,0004,471≈57 records per taxi\frac{255{,}000}{4{,}471} \approx 57 \text{ 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 name package.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 provided scope
  • Cluster gone next session → EMR stops with the lab / after 3 h idle → use Clone to recreate it with the same settings