Introduction to Hadoop and MapReduce
Introduction to Hadoop and MapReduce
Module-02
Introduction to Hadoop and Map Reduce Programming
.IN
Introduction to Hadoop
computers.
• Understanding Hadoop is crucial due to the exponential growth of data generated daily by
enterprises worldwide.
U
• Big Data refers to the huge volumes of diverse data generated every second, minute, and
day.
• Enterprises are increasingly recognizing Big Data as a valuable resource for insights and
innovation.
• Every Day:
• Every Minute:
• Every Second:
.IN
The Need for Hadoop
• To handle, process, and analyze the vast and varied data efficiently, a scalable system like
C
Hadoop is essential.
• Hadoop addresses challenges related to storing and processing colossal volumes of data
N
by distributing the workload.
SY
• Allows for more precise analysis — the more data available, the better the accuracy of
insights.
Hadoop is widely adopted because of its ability to handle massive amounts of data, in
varied formats, and process it quickly. Here's a breakdown of the key points:
.IN
Other Considerations for Using Hadoop (Figure 5.2):
1. Low Cost
C
o Open-source framework
N
o Uses commodity hardware, which is inexpensive and easy to obtain.
2. Inherent Data Protection
SY
4. Scalability
o Can scale horizontally by adding more machines (nodes).
VT
5. Computing Power
o Distributed processing allows for parallel computation, reducing processing time.
Hadoop provides a cost-effective, scalable, and efficient way to manage the challenges
of Big Data—making it one of the most in-demand technologies in data-driven enterprises.
1. Computing Power
2. Scalability
.IN
o Requires minimal system administration as the system grows.
3. Storage Flexibility
C
o Unlike traditional RDBMS, no need to pre-process data before storing it.
N
o Can store structured, semi-structured, and unstructured data like images,
videos, text.
SY
• Data is:
.IN
5.3 Why Not RDBMS?
• RDBMS is not ideal for:
C
o Handling large files, images, and videos.
N
o Advanced analytics and machine learning workloads.
SY
• Requires:
• As data size increases (e.g., TB → PB), cost per GB grows rapidly with RDBMS.
Relational Database
.IN
System Node-Based Flat Structure
Management System
~$10,000–$14,000 per
Cost ~$4,000 per terabyte
terabyte
• Hadoop originated as a part of the Apache Nutch project (an open-source web search
engine).
• It's a made-up name given by Doug Cutting’s son to a stuffed yellow toy elephant.
o Easy to pronounce
.IN
C
N
SY
U
Year Event
2002 Doug Cutting and Mike Cafarella started working on Nutch.
VT
What is Hadoop?
Aspect Description
Open Source
Free to download, use, and contribute to.
.IN
Software
Includes tools, programs, and infrastructure needed for development and
Framework
execution. C
Distributed Data is divided and stored across multiple machines. Processing is parallelized.
Faster Processing Enables quick response times by processing data in parallel across nodes.
U
VT
.IN
2. MapReduce
.IN
o Master Node = NameNode
1. Data Integration:
VT
▪ Sales data
.IN
• Helps understand customer purchasing behavior
1. Data Integration:
▪ Sales data
o Allows:
.IN
C
N
SY
5. Replication:
o Files can be replicated multiple times (configurable), making the system tolerant
to hardware/software failures
7. Designed for large files (e.g., GBs to TBs) — optimized for reading/writing large
datasets
• Each block is replicated across nodes in the cluster according to the default
replication factor (usually 3)
.IN
[Link] NameNode
2. Transaction Logging:
o On startup, NameNode:
3. Rack Awareness:
o Uses Rack ID to identify the DataNodes in different racks (helps in fault tolerance
and efficient data transfer).
Prof. Deepika G, Dept. of CSE, SVIT Page 13
Studied smart, not hard — thanks to [Link]
4. Single NameNode per Hadoop cluster.
.IN
C
N
SY
U
VT
2. DataNodes communicate with each other and the NameNode during read/write
operations.
7. This allows the system to keep functioning smoothly even if a DataNode goes down.
• The manager (like the NameNode) assigns tasks only to those who have checked in.
• If no swipe (heartbeat), the employee (DataNode) is considered absent, and tasks are
reassigned.
.IN
C
N
SY
U
VT
o The client uses open() to request a file via the DistributedFileSystem (DFS).
o DFS contacts the NameNode to get the locations (addresses) of the DataNodes
storing the file's data blocks.
o The client reads the file data block-by-block, starting with the closest DataNode.
o When the reading is complete, the client calls close() to close the
FSDataInputStream.
Flow:
.IN
open() → DFS → NameNode → Block locations → FSDataInputStream → Read from
DataNode(s) → close()
C
N
SY
U
VT
o NameNode does checks (e.g., if file already exists) and creates a file without data
blocks initially.
o Data is split into packets, placed into a data queue, and processed by
DataStreamer.
.IN
4. Data Packets Streamed to DataNodes
5. Acknowledgment Process
o A packet is removed from this queue only when all three DataNodes have
acknowledged it.
o Once all data is written, the client calls close() on the stream.
Flow:
1. First Replica
2. Second Replica
3. Third Replica
o Placed on the same rack as the second replica, but on a different node.
.IN
Display file content hadoop fs -cat /sample/[Link]
HDFS.
Copies file from one HDFS
Copy file within HDFS hadoop fs -cp /sample/[Link] /sample1
C dir to another.
Remove directory from hadoop fs -rm -r /sample1
Deletes directory and
HDFS contents from HDFS.
N
SY
Data Replication
• HDFS automatically directs the client to the nearest replica for better performance.
VT
Data Pipeline
• That DataNode forwards it to the second, and then to the third, forming a pipeline.
What is MapReduce?
• It splits the data into parts and processes each part at the same time.
How It Works
1. Map Task
o The outputs from all mappers are shuffled and sorted by keys.
3. Reduce Task
Key Features
.IN
• Data Locality: Tries to run the task where the data is stored to save time.
1. JobTracker (Master)
.IN
• Only one JobTracker per cluster.
2. TaskTracker (Worker) C
• Executes the actual Map or Reduce tasks given by JobTracker.
N
• One TaskTracker per slave node.
• If JobTracker doesn't get a heartbeat, it assumes failure and reassigns the task.
U
o There is one JobTracker (the master) that controls the whole job.
o There are many TaskTrackers (workers) that do the actual work on the data.
3. Map Tasks
o They perform the map function, which processes the data and creates key-value
pairs (like labeling the data).
o The output from the map tasks is shuffled and sorted by keys automatically by
the framework.
o They combine or summarize the data based on the keys, producing the final
result.
6. Output
o The final combined output is saved or sent back to the user program.
Roles
.IN
• JobTracker: Master controller that assigns tasks to workers.
The famous example for MapReduce Programming is Word Count. For example, consider you
need to count the occurrences of similar words across 50 files. You can achieve this using
MapReduce Programming. Refer Figure 5.25.
3. Reducer Class: This class overrides the Reduce Function based on the problem
statement.
.IN
C
N
SY
U
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link]([Link](true) ? 0 : 1);
}
.IN
}
import [Link];
import [Link];
import [Link];
import [Link];
U
@Override
protected void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
String[] words = [Link]().split(",");
for (String word : words) {
[Link](new Text(word), new IntWritable(1));
}
}
}
package [Link];
import [Link];
import [Link];
import [Link];
.IN
[Link](word, new IntWritable(count));
}
}
C
N
5.12 MANAGING RESOURCES AND APPLICATIONS WITH HADOOP YARN (YET ANOTHER
RESOURCE NEGOTIATOR)
SY
Apache Hadoop YARN is a sub-project of Hadoop 2.x. Hadoop 2.x is YARN-based architecture.
It is a general processing platform. YARN is not constrained to MapReduce only. You can run
multiple applications in Hadoop 2.x in which all applications share a common resource
U
management. Now Hadoop can be used for various types of processing such as Batch,
Interactive, Online, Streaming, Graph, and others.
VT
In Hadoop 1.0, HDFS and MapReduce are Core Components, while other components are built
around the core.
1. Single NameNode is responsible for managing entire namespace for Hadoop Cluster.
.IN
1. Namespace (manages files and directories)
Uses multiple independent NameNodes that don’t need to coordinate with each other.
• Active-Passive NameNode setup where passive node takes over automatically if active
node fails.
• Passive NameNode reads from shared storage and keeps metadata updated.
• If active NameNode fails, passive becomes active and continues writing to shared
storage.
Key Components:
1. Global ResourceManager:
2. NodeManager:
3. Per-application ApplicationMaster:
.IN
[Link].2 Basic Concepts of YARN
Basic Concepts
C
Application:
N
1. A job submitted to the YARN framework.
SY
Container:
U
o Example:
5. Launching Containers:
7. Execution by NodeManager:
8. The NodeManager runs the application code and reports progress, status, etc., back to
.IN
the ApplicationMaster using a specific protocol.
9. Client Communication:
10.
C
The client that submitted the job talks directly to the ApplicationMaster to
receive job updates (e.g., status, progress), also via a protocol.
N
11. Completion & Shutdown:
SY
Introduction
• MapReduce jobs are split into map tasks and reduce tasks, executed on a Hadoop
cluster.
• Each task processes a small portion of the data, allowing Hadoop to distribute the
load.
.IN
Map tasks handle:
• Output from map tasks = intermediate keys and values, sent to reducers.
• Hadoop runs map tasks where the data is stored (DataNode) to reduce network usage
and save bandwidth.
8.2 Mapper
1. RecordReader – Converts raw byte data into record-oriented form, giving key–
value pairs to the mapper.
2. Map – Processes the input pairs to produce zero or more intermediate pairs.
8.3 Reducer
Reducer’s job: Take intermediate values with the same key and reduce them into a smaller
set.
1. Shuffle and Sort – Collects outputs from all partitioners, downloads them to the
.IN
reducer’s local machine, and sorts them by key so similar items are grouped
together.
2. Reduce – Processes each group of values for a key (e.g., sum, filter, aggregate, or
C
combine data), producing zero or more output key–value pairs.
N
3. Output Format – Writes the final key–value pairs to a file (default separator is a
tab).
SY
• Figure 8.1 shows how data flows through Mapper → Combiner → Partitioner → Shuffle
& Sort → Reducer.
U
VT
• Use case example: Counting occurrences of similar words in a file before sending to
Reducer.
.IN
• How it works:
o Set the combiner class in the driver program (often same as Reducer class).
C
o Runs locally on Mapper output to aggregate data early.
N
• Sample code:
SY
[Link]([Link]);
• Execution:
VT
hadoop jar <jar name> <driver class> <input path> <output path>
python-repl
CopyEdit
hadoop 2
hive 2
pig 1
session 3
...
Purpose:
• Runs after the Map phase and before the Reduce phase.
.IN
Example task: Count occurrences of similar words and partition them based on the first
alphabet.
How it works:
C
• Custom WordCountPartitioner checks the first letter of the word.
N
• Assigns a partition number (1–26 for A–Z, plus default).
SY
• Ensures that all words starting with the same letter go to the same reducer.
U
VT
Code: [Link]
import [Link];
import [Link];
import [Link];
switch (alphabet) {
case 'A': partitionNumber = 1; break;
case 'B': partitionNumber = 2; break;
case 'C': partitionNumber = 3; break;
case 'D': partitionNumber = 4; break;
case 'E': partitionNumber = 5; break;
case 'F': partitionNumber = 6; break;
case 'G': partitionNumber = 7; break;
case 'H': partitionNumber = 8; break;
case 'I': partitionNumber = 9; break;
case 'J': partitionNumber = 10; break;
.IN
case 'Y': partitionNumber = 25; break;
case 'Z': partitionNumber = 26; break;
default: partitionNumber = 0; break;
}
return partitionNumber;
}
C
}
N
SY
Path("/mapreducedemos/output/wordcountpartitioner/"));
The objective: To write a MapReduce program to search for a specific keyword in a file.
In this case, the program scans an input file (e.g., [Link]) and finds lines containing the
given keyword ("Jack"), then outputs the matching record along with its filename and position
in the file.
import [Link];
.IN
import [Link];
import [Link];
import [Link];
import [Link];
C
import [Link];
import [Link];
N
import [Link];
SY
import [Link];
ClassNotFoundException {
Configuration conf = new Configuration();
VT
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
[Link]([Link](true) ? 0 : 1);
}
}
.IN
2. Mapper — [Link]
import [Link];
import [Link];
C
import [Link];
N
import [Link];
import [Link];
SY
import [Link];
import [Link];
U
@Override
protected void setup(Context context) throws IOException, InterruptedException {
Configuration configuration = [Link]();
keyword = [Link]("keyword");
}
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException,
InterruptedException {
FileSplit fileSplit = (FileSplit) [Link]();
String fileName = [Link]().getName();
pos++;
if ([Link]().contains(keyword)) {
[Link](value, new Text(fileName + "," + pos));
import [Link];
import [Link];
import [Link];
.IN
@Override
protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException,
InterruptedException {
for (Text value : values) {
C
[Link](key, value);
N
}
}
SY
1001,John,45
1002,Jack,39
VT
1003,Alex,44
1004,Smith,38
1005,Bob,33
1002,Jack,39 [Link],2
8.7 Sorting
3. Corrected Code
[Link]
import [Link];
.IN
import [Link];
import [Link];
import [Link];
import [Link];
C
import [Link];
N
import [Link];
import [Link];
SY
import [Link];
import [Link];
import [Link];
U
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
.IN
[Link]([Link]);
[Link]([Link]);
C
[Link](job, new Path(args[0]));
[Link](job, new Path(args[1]));
N
[Link]([Link](true) ? 0 : 1);
SY
}
}
U
4. How to Run
hadoop jar [Link] SortStudNames /mapreduce/[Link]
VT
/mapreduce/output/sorted
5. Expected Output
Hadoop sorts keys (names) alphabetically, so output will be:
1003,Alex,44
1005,Bob,33
1002,Jack,39
1001,John,45
1004,Smith,38
6. Summary
• Input: CSV with IDs, Names, Scores.
• Processing: Sort by name (second field).
• Output: Alphabetically sorted list of students.
• Key Trick: Use the student name as the Mapper output key so Hadoop handles sorting
automaticall
[Link]("[Link]", true);
[Link]("[Link]",
[Link],
.IN
[Link]);
o GzipCodec → compression algorithm.
o CompressionCodec → interface for compression/decompression.
• Effect: Output files are compressed in .gz format.
C
N
SY
U
VT