Lecture 6 - MapReduce Framework and Programming
Roadmap
- MapReduce Concept
- Mapper
- Reducer
- Combiner
- Partitioner
- MapReduce Job
- Create your first program
- Wordcount
- Execute job
- Launch AWS EMR
Typical Large-Data Problem
- Iterate over a large number of records
- Extract something of interest from each
- Group intermediate results
- Aggregate intermediate results
- Write final output
[Image: Diagram showing Split 1/2/3 → workers (w1, w2, w3) → results (r1, r2, r3) → combined "Result"]
Think of it like a big group project: you split the giant textbook into chapters (splits), each classmate (worker) reads their chapter and makes notes (intermediate result), then you combine everyone's notes into one final summary.
Divide and Conquer
Related
- When dealing with large data that needs processing, Divide and Conquer can be used. It has three steps:
- Divide: dividing the problem into smaller sub-problems
- Conquer: solve sub-problems by calling recursively until solved
- Combine: combine the sub-problems to get the final solution of the whole problem
[Image: Diagram showing "Work" split into w1/w2/w3 → workers → r1/r2/r3 → "Result", labeled Partition (left) and Aggregation (right)]
Parallelization Challenges
- How do we assign work units to workers?
- What if we have more work units than workers?
- What if some workers are slower than others?
- What if workers need to share partial results?
- How do we aggregate partial results?
- How do we know all the workers have finished?
- What if workers die?
Common theme: All of these are coordination/reliability problems — this is exactly what the MapReduce framework is designed to solve for you.
What is MapReduce?
- MapReduce is a programming framework that allows us to perform distributed and parallel processing on large data sets in a distributed environment
- Allows us to perform parallel computations without bothering about issues like reliability, fault tolerance, etc.
- MapReduce consists of two distinct tasks — Map and Reduce
[Image: Diagram showing Input (Split 0-4) → Map Phase (Map()) → Shuffle Phase → Reduce Phase (Reduce()) → Output 1, Output 2]
Like a warehouse: workers (mappers) each sort through their own bin of items and tag them; then all the "socks" tags get shuffled to one person and all the "shirts" tags to another (reducers), who count/aggregate them into a final report.
MapReduce Framework
- MapReduce consists of two distinct tasks — Map and Reduce for calculation
[Image: Diagram showing (a) Map: input → map → list(k2,v2); (b) Shuffle: group values by keys; (c) Reduce: reduce → list(k3,v3)]
MapReduce: How It Works (Word Count Example)
- Word Count example flow: Input → Splitting → Mapping → Shuffling → Reducing → Final result
[Image: Word Count diagram — "Deer Bear River / Car Car River / Deer Car Bear" split into 3 lines, each mapped to word-count pairs, shuffled by key, reduced to totals: Bear 2, Car 3, Deer 2, River 2]
- Notation used throughout:
- — input key-value pair
- — mapper output (intermediate)
- — after shuffling (grouped by key)
- — reducer output (final)
MapReduce: Map Task
- The Map function takes input from disk as pairs, processes them, and produces another set of intermediate pairs as output
- The input data is first split into smaller blocks. Each block is assigned to a mapper for processing
- Example: if a file has 100 records to process, 100 mappers can run together (one record each), or 50 mappers can run together (two records each)
- The Hadoop framework decides how many mappers to use, based on the size of the data and the memory block available on each mapper server
Example:
- Doc1, [dear bear river] → dear,1 / bear,1 / river,1
- Doc2, [car car river] → car,1 / car,1 / river,1
Think of the mapper as a person going through a receipt and writing down each item name with a "1" next to it — no totaling yet, just listing.
MapReduce: Shuffling and Sorting
- Shuffling
- Process by which the mapper's intermediate output is transferred to the reducer. Reducer gets one or more keys and associated values based on reducers
- No processing, just group intermediate result by key
- Sorting
- Before the reducer starts, all intermediate key-value pairs get sorted by key (not by value)
- Sort Key
[Image: Diagram showing Mapping output list(<k2,v2>) → Shuffling → grouped output <k2, list(v2)>, e.g. (Bear, [1,1]), (Car, [1,1,1]), (Deer, [1,1]), (River, [1,1])]
Imagine mail sorters grouping all the letters addressed to the same person into one bundle before delivery — that's shuffling. Sorting is like alphabetizing those bundles by recipient name.
MapReduce: Reduce Task
- Reduce task mostly aggregates intermediate results. It also takes inputs as pairs, and produces another pair as output
- After all mappers complete processing, the framework shuffles and sorts the results before passing them to the reducers
- A reducer cannot start while a mapper is still in progress. All map output values with the same key are assigned to a single reducer, which then aggregates the values for that key
[Image: Diagram showing shuffled grouped pairs (Bear,[1,1]), (Car,[1,1,1]), (Deer,[1,1]), (River,[1,1]) → final result Bear 2, Car 3, Deer 2, River 2]
Like a cashier finally tallying up how many of each item were bought across all receipts, once all the receipts (mappers) are in.
MapReduce: Code
- Call
Emit(key, value)any number of times to create an output document associating a key with a value
Map(String docid, String text):
for each word w in text:
Emit(w, 1);
Reduce(String word, Iterator<Int> counts):
int sum = 0;
for each v in counts:
sum += v;
Emit(word, sum);
Emitis just the mapper/reducer's way of saying "record this result" — like writing a line into a notebook.
MapReduce: Indexing Example
- We want to identify documents that have a particular word/term (this is an inverted index — used in search engines)
[Image: Diagram showing Collection (Documents, IDs: A="Clinton Trump Clinton", B="Clinton Sanders", C="Clinton Barack Trump") → Inverted Index (Terms, Posting Lists: Clinton→A,2 B,1 C,1 / Trump→A,1 C,1 / Sanders→B,1 / Barack→C,1)]
[Image: Diagram showing map/shuffle/reduce flow for the indexing example: each document mapped to (word, docID) pairs, shuffled by word, reduced into posting lists like Clinton→[A(2), B(1), C(1)]]
Just like the index at the back of a textbook that tells you which pages mention "photosynthesis" — MapReduce builds that list automatically by having each mapper report "this word is in this document," then the reducer collects all the reports for each word.
MapReduce: Indexing Code
- Map function: loop over all words and create , e.g.
- Reduce function: for each word, loop over the list of doc IDs and create final output as
Map(String docid, String text):
for each word w in text:
Emit(w, docid);
Reduce(String word, Iterator<String> values):
HashMap map = new HashMap();
for (Text val : values) {
if (map.containsKey(val))
map.put(val, map.get(val) + 1);
else
map.put(val, 1);
}
Emit(word, map.toString());
Optional Tasks: Combiner and Partitioner
- Combiner: combine data locally → reduce size of intermediate data
- Partitioner: dividing up the intermediate key space to match the number of reducers
[Image: Diagram showing (a) Map: input → map → combine → partition (repeated across 4 rows) → (b) Shuffle: group values by keys]
Optional Tasks: Combiner
- Combiner works in between Mapper and Reducer. The output produced by the Mapper is intermediate output in terms of key-value pairs which is massive in size. If we directly feed this huge output to the Reducer, it results in increasing Network Congestion
- Group or aggregate data before passing to Shuffle
- Combiners are also known as semi-reducer or local reduce
[Image: Diagram showing Input → Mapping → Combiner (local aggregation, e.g. Deer,1/Bear,1/River,1) → Shuffling → Reducing → Final Result (Bear 2, Car 3, Deer 2, River 2)]
Think of the combiner as pre-sorting your recycling at home before sending it to the central recycling plant — it reduces the volume of "stuff" that needs to travel and be processed downstream.
Optional Tasks: Partitioner
- It makes sure all reducers handle data equally. Divides up key space for parallel reduce operations — a simple hash of the key mod n
- The number of partitioners equals the number of reducers. A partitioner divides the data according to the number of reducers. Therefore, data from a single partitioner is processed by a single Reducer
[Image: Table showing example keys with Hash and Hash%5 values, e.g. Key1: 874253 → 3, Key2: 352461 → 1, etc.]
[Image: Diagram showing Input → Mapping → Combiner → Partitioner (assigns Bear/Car/Deer/River to specific reducer buckets) → Shuffling → Reducing → Final Result]
Like assigning tables at a restaurant based on the last digit of a customer's reservation number — it evenly spreads customers (keys) across a fixed number of waiters (reducers).
Roadmap (continued)
- MapReduce Job
- Create your first program
- Wordcount
- Execute job
- Launch AWS EMR
MapReduce Job: Steps
[Image: Diagram showing User Program → (1) submit → Master → (2) schedule map/reduce → workers reading splits (3) read → local write (4) → remote read (5) → output files (6) write]
Steps overview:
- User Program submits the job
- Master schedules map and reduce tasks
- Workers read input splits
- Workers write intermediate output locally
- Reduce workers remote-read the intermediate data
- Reduce workers write final output files
Create Your First Program: Word Count
- Prepare Java Development Environment
- Prepare library for Hadoop and MapReduce
- Create Mapper class
- Create Reducer class
- Create Main program
- Build Jar file
- Upload Jar file to Hadoop cluster
- Upload data file to HDFS
- Execute job
Prepare Java Development Environment
- Use Eclipse for Java Development with JDK 1.8
- Create project
MRWordcount - Create three files:
WordCountDriver,WordCountMapper,WordCountReducer - Create folder
liband copy Hadoop and MapReduce lib to thelibfolder
[Image: Screenshot of Eclipse Package Explorer showing MRWordCount project structure, and Java Build Path dialog showing hadoop-common and hadoop-mapreduce-client-core jars added]
Create Mapper Class
- For each line, split with white space and iterate over the word
- Output with word as key and one as value
public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable>{
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);
}
}
}Create Reducer Class
- For each key, sum the number of occurrences of the word over the input (intermediate output from mapper)
- Output with word as key and sum of value
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));
}
}Create Main Class
- Configure Job, assign name and main class
- Set Mapper and Reducer
- Set Output key and value
- Set Input and Output path
- Execute the job
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);
}
}Build Jar File
- Right click at project and select Export
- Select Java → JAR file
- Select resource
- Select export destination
- Path
- Filename
- Finish
[Image: Screenshots of Eclipse Export wizard — selecting JAR file export type, and JAR File Specification dialog with resources checked and destination path set to MRWordCount.jar]
Output: MRWordCount.jar
Upload Jar File to Hadoop Cluster
- Connect to Hadoop cluster via ssh
- You can use Mobaxterm software
[Image: Screenshot of Mobaxterm SSH session connected to Hadoop master node (203.159.10.50), showing directory listing with MRWordCount.jar present]
Upload Data to HDFS
- First upload the file to the Hadoop cluster (local path), e.g.
document.txt - Use
mkdircommand to create an input directory in HDFS - Use
putcommand to copy the input file (document.txt) to the input directory of HDFS - Use
lscommand to verify the files in the input directory of HDFS
$HADOOP_HOME/bin/hadoop fs -mkdir input_dir
$HADOOP_HOME/bin/hadoop fs -put /home/hadoop/document.txt input_dir
$HADOOP_HOME/bin/hadoop fs -ls input_dirExecute MapReduce Job
- Use
jarcommand to run the MapReduce program in the jar file - Output directory will be created automatically
$HADOOP_HOME/bin/hadoop jar MRWordCount.jar WordCountDriver input_dir output_dir[Image: Terminal output showing job submission log, tracking URL, "map 0% reduce 0%" progressing to "map 100% reduce 100%", and "Job ... completed successfully"]
Check Result
- Use
catcommand to view the output. Better to uselsfirst to check files part-r-00000is the output file. If the input file is very large, the output may have multiple files — equal to the number of reducers
$HADOOP_HOME/bin/hadoop fs -cat output_dir/part-r-00000[Image: Terminal output showing word-count results from cat command, e.g. "DBO.NF_PLACE", 4 / IBIS, 4 / PLACE_ID, 4, etc.]
Roadmap (continued)
- Launch AWS EMR
Hadoop on Cloud: AWS EMR
- EMR has multiple deployment options
[Image: Tree diagram — EMR splits into: EMR on EC2 (→ Custom Scaling / Managed Scaling → Instance Group / Instance Fleet), EMR on EKS (→ EC2 → Karpenter/Cluster Autoscaler; → Fargate), and EMR Serverless]
Source: https://medium.com/nerd-for-tech/aws-elastic-map-reduce-intro-55206fd47c85
AWS EMR: Component
- Cluster: a collection of EC2 instances called Nodes. Based on the role of the node, they are categorized into three types: Master, Core, and Task Node
[Image: Diagram showing a Cluster of 4 Node/EC2 instances zoomed into Master Node (Name Node, YARN Resource Manager), Core Node (Data Node, YARN Node Manager, Application Master, Executors/Task), Task Node (Executors/Task)]
- Master Node: Manages & monitors the cluster and coordinates the distribution of data and tasks among other nodes. It also tracks the status of tasks
- Core Node: Nodes that hold data and execute tasks
- Task Node: Provides extra compute power. Does not hold any data
Master = manager, Core = worker with storage, Task = extra temp worker with no storage of their own (like hired seasonal help who don't keep inventory).
Source: https://medium.com/nerd-for-tech/aws-elastic-map-reduce-intro-55206fd47c85
AWS EMR: Storage Layer
- AWS provides three options for the storage layer:
- HDFS using EBS (
hdfs://master-ip-address/path-to-data) - EMRFS using S3 (
s3://bucket-name/path-to-file-in-bucket) - HDFS using Instance store
- HDFS using EBS (
[Image: Icons for Amazon EBS, Amazon S3, Amazon EC2 Instance Store]
- Data Loss risk (for instance store) occurs when:
- The underlying disk drive fails
- The instance stops
- The instance hibernates
- The instance terminates
- (Reboot is OK)
Source: https://medium.com/nerd-for-tech/aws-elastic-map-reduce-intro-55206fd47c85
Hadoop on Cloud: AWS EMR (Workflow)
- With Amazon EMR you can set up a cluster to process and analyze data with a big data framework
[Image: "EMR Workflow" diagram with three columns — Plan & Configure (Plan storage → Choose big data frameworks → Develop apps and scripts → Select hardware → Set up networking → Configure security → Launch a cluster), Manage (Connect → Submit work → View results → Monitor → Troubleshoot → Scale), Clean Up (Terminate the cluster → Delete resources), with legend: solid=Essential, dashed=Best Practice, dotted=Optional]
AWS EMR: Lifecycle of a Cluster
- Once you launch a cluster, it will enter multiple stages and end with WAITING — meaning ready to use
[Image: Flowchart — Launch cluster (STARTING) → Run bootstrap actions (BOOTSTRAPPING) → if successful → Process steps (RUNNING) → Waiting for instructions (WAITING) ↔ User adds steps loop; if not successful at any stage → Shut down cluster (TERMINATING) → Processing failed (TERMINATED_WITH_ERRORS); from WAITING, if configured to auto-terminate and processing completed → TERMINATING → TERMINATED; or User terminates cluster → TERMINATING → TERMINATED]
Hadoop on Cloud: AWS EMR (Console)
- Access to AWS Learner Lab (50 USD credits)
- Select EMR service and click "Create cluster"
[Image: Screenshot of AWS EMR console showing "EMR on EC2: Clusters" page with no clusters and a "Create cluster" button]
AWS EMR: Choose Big Data Framework
- Define Cluster Name
- Select EMR version — it matches with some version of the Hadoop ecosystem
- Select only the services you want:
- Hadoop
- Hive
[Image: Screenshot of "Create cluster" form — Name field, Amazon EMR release dropdown (emr-5.29.0), Application bundle options (Spark, Core Hadoop, HBase, Presto, Custom), checkboxes for Flink, HCatalog, Hue, MXNet, Phoenix, Spark, Tez, Ganglia, Hadoop 2.8.5 (checked), JupyterHub, Mahout, Pig, Sqoop, Zeppelin, HBase, Hive 2.3.6 (checked), Livy, Oozie, Presto, TensorFlow, ZooKeeper]
AWS EMR: Select Hardware
- Select Instance groups, Primary node and 2 Core nodes (No task node)
[Image: Screenshot of Cluster configuration form — Instance groups selected, Primary node set to m4.large, Core node set to m4.large, Cluster scaling option "Set cluster size manually" with Core instance size = 2]
AWS EMR: Select Network
- Use default VPC and subnet
[Image: Screenshot of Networking form showing VPC ID, Subnet ID, and EC2 security groups for Primary node and Core/task nodes (EMR-managed security groups)]
AWS EMR: Assign Security Key Pair
- For remote access to the cluster, assign a security key pair
- Keypair downloaded from AWS detail of learner lab
- Download PEM
[Image: Screenshot of "Security configuration and EC2 key pair" form with key pair "vockey" selected, and AWS Learner Lab panel showing "Download PEM" / "Download PPK" buttons]
AWS EMR: Assign Instance Profile and Service Role
- Instance profile assigns a role to every EC2 instance in a cluster
- Assign Service Role
[Image: Screenshot showing "EC2 instance profile for Amazon EMR" set to EMR_EC2_DefaultRole, and "Amazon EMR service role" set to EMR_DefaultRole]
AWS EMR: Create Cluster
- Click Create cluster
- It may take up to 10 minutes for the cluster to start
[Image: Screenshot of cluster summary page "My cluster" with Status: Starting, Cluster ID, EMR version 5.29.0, Hadoop 2.8.5, Hive 2.3.6 installed]
AWS EMR: Ready to Use
- Wait until status shows Waiting
- Use Primary node public DNS for remote connection
[Image: Screenshot of cluster summary showing Status: Waiting, Primary node public DNS (ec2-3-91-90-3.compute-1.amazonaws.com), "Connect to the Primary Node using SSH" link]
AWS EMR: Add SSH Allow on Firewall
- Go to security group of the primary node
- Click link and select Edit inbound rule
- Add new rule with SSH, Anywhere-IPv4
- Save Rule
[Image: Screenshot of EC2 security group inbound rules editor, adding an SSH rule with source Anywhere-IPv4 (0.0.0.0/0)]
Use Mobaxterm to Remote SSH to EMR
- For Windows: https://mobaxterm.mobatek.net/download.html
- Select Home Edition (Free)
[Image: Screenshot of Mobaxterm Home Edition feature list (Free) alongside a Mobaxterm session window]
Session settings:
- Host: copy from primary node DNS (e.g.
ec2-3-91-90-3.compute-1.amazonaws.com) - User:
hadoop - Private key: download PEM from AWS detail of Learner Lab
[Image: Screenshot of Mobaxterm SSH session settings — Remote host field, username "hadoop", Advanced SSH settings with "Use private key" pointing to a .pem file]
Ready to Run MapReduce!
- If it works, you should see the EMR logo and a prompt for running CLI
[Image: Terminal screenshot showing Amazon Linux AMI welcome banner and large ASCII-art "EMR" logo, ending with hadoop@ip-172-31-35-141 prompt]
- Run MapReduce code:
ls
mv error.txt document.txt
hadoop fs -mkdir /wordcount
hadoop fs -put document.txt /wordcount
hadoop jar MRWordCount.jar WordCountDriver /wordcount /wordcount_output[Image: Terminal screenshot showing job submission log with "map 0% reduce 0%" progressing to "map 100% reduce 100%" and "Job ... completed successfully", Counters: 50]
Summary
- MapReduce Concept
- Mapper
- Reducer
- Combiner
- Partitioner
- MapReduce Job
- Create your first program
- Wordcount
- Execute job
- Launch AWS EMR