In this post, we will discuss the following with regards to MapReduce framework :-
- Motivation for a parallel processing framework
- What is MapReduce?
- How MapReduce solves a problem?
- MapReduce in detail
- Map Phase
- Shuffle & Sort Phase
- Reduce Phase
Motivation for a parallel processing framework
As you know we are living in the age of Data. Today the size of internet is almost 40+ billion web pages. If we assume that each page has 20Kb of data, we looking at somewhere close to 800+ terabyte of data. With the reading speed of 100 Mbps, it will take a computer more than 4 months to read the web. And just to store such huge data, we will need 1000’s of computers.
Clearly we need a mechanism to divide such huge work among various computers. If we give the same work of reading 400+ terabytes of data to say 1000 computers, it can be done in less than 3 hours.
But our task is not limited to reading data. We need also need to process such massive data. Clearly consolidating the data from the nodes and transferring it to the compute nodes will take a lot of time. We therefore need a programming framework that allows for distributing the computation task and running them in parallel.
What is MapReduce?
MapReduce is one such programming model designed for processing large volumes of data in parallel by dividing the work into a set of independent tasks.1 Each of these tasks are then run on individual node in a cluster. The advantage of MapReduce framework is that, it not only divides the work but also also abstracts the programmer from all the issues that come with distributed computing such as communication and coordination, recovering from machine failure, status reporting, debugging, optimization and data locality.
How MapReduce solves a problem?
A typical problem solved by MapReduce can be broken down into the following steps :-
- Read a lot of data
- Extract something you are interested in from every record
- Shuffle and sort the intermediate results
- Aggregate (filter, sort or transform) the intermediate result
- Write out the result
MapReduce in detail
The figure below will give you an overview of MapReduce. In MapReduce everything is in terms of key-value pairs. The phases of the MapReduce task are Map, Sort & Shuffle and Reduce.
The two Daemons associated with MapReduce are JobTracker and TaskTracker. The Client submits the job to the master node which runs the JobTracker. The JobTracker then assigns Map and Reduce tasks to other nodes in the cluster. These nodes run the TaskTracker daemons that starts the Map and Reduce tasks on the nodes and send the progress report to the JobTracker. So basically JobTracker is the MasterNode and TaskTrackers are the slaves.
Map Phase
One of the major advantages of using Hadoop is Data Locality. Hadoop always tries to take the computation to the data rather than to transfer data to the computation node. In other words a node is made the Mapper that is closest to the data (if possible the same node that has the data is made the mapper). This greatly reduces the network traffic and the time to transfer data from one node to another.
If you can see the figure above, multiple mappers run the Map tasks in parallel, each processing a portion if the input data. The Mappers receives the input interms of key-value pairs. It then emits a list of intermediate key and value pair (zero of more).
map(key, value) -> (intermediate_key, intermediate_value)
Map is essentially a function that takes a key-value pair as input and emits intermediate key-value pair. Let us concrete our understanding by taking an example of “word frequency” Mapper. Here our goal is to find the frequency of the words in a document. The key here is the offset of the word (where the word is found in the document) and the value is the word itself. When this is passed to the Mapper, it emits the word as key and 1 as the value.
For instance, let the document be “to be or not to be”.
So the Map function would look something like,
map(k, v) = (v, 1)map(offest1, 'to') = ('to', 1)map(offest2, 'be') = ('be', 1) map(offest3, 'or') = ('or', 1)map(offest4, 'not') = ('not', 1)map(offest5, 'to') = ('to', 1)map(offest6, 'be') = ('be', 1)Sort & Shuffle phase
After all the Map phases are complete, every pair has an intermediate key and value. Now all the values that have the same key are combined together and then they are sorted. This is the sort and shuffle phase of MapReduce. It is important to note that the output of the Map phase is stored on the local hard disk and not on the HDFS.
Continuing with our example, the output after Sort & Shuffle phase will be,
('to', [1, 1]), ('be', [1, 1]), ('or', [1]), ('not', [1])Reduce Phase
After the Sort & Shuffle phase, the intermediate lists of key-value pair is fed to the Reducer, where it is subjected to the Reduce function. The Reducer emits zero/more final key value pair. Usually, a reducer will emit one key value pair for every intermediate key. The output of the Reducer is written on to the HDFS.
The Reduce function here will be to add all the intermediate values associated with a particular key. So the final output will be,
('to', 2), ('be', 2), ('or', 1)
As you see, the Reducer will give us the required output (which is the word frequency in the document).
To conclude, I reiterate that MapReduce is a great abstraction that allows programmers to focus only on the problem rather that all the messy details that need to be looked into while programming for large scale distributed development.
Its finally time to attempt our first MapReduce program. As with any programming language the first program you try is “Hello World”. We execute “Hello World” because it the easiest and we test whether the everything is perfectly installed and configured.
The easiest problem in MapReduce is the word count problem and is therefore called MapReduce’s “Hello World” by many people. So let us dive into it.
In the word count problem, we need to find the number of occurrences of each word in the entire document. I already explained how the map, shuffle & sort and reduce phases of MapReduce taking this example.
We will use eclipse provided with the Cloudera’s Demo VM to code MapReduce.
Step 1: Create a new project – Open eclipse. Add a new Java Project and name it as “wordCount”.
Step 2: Setup the Library – Right click on the newly created wordCount project and click on “Properties”. Select “Java Build Path” from the left panel. Click “Add external JARs..”.
- Add all the JARs from /usr/lib/hadoop/client-0.20
- Add “hadoop-annotations.jar”, “hadoop-auth.jar” and “hadoop-common.jar” from /usr/lib/hadoop
- Add “hadoop-httpclient-3.1.jar” from /usr/lib/hadoop/lib
Step 3: Code the Mapper – To run MapReduce jobs we need three things: Map function, Reduce function & some code to run the job (also known as driver). For Map function we will write a Mapper class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
| 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 context) throws IOException, InterruptedException { String line = value.toString(); //Split the line into words for(String word: line.split("\\W+")) { //Make sure that the word is legitimate if(word.length() > 0) { //Emit the word as you see it context.write(new Text(word), new IntWritable(1)); } } }} |
As you see the WordCountMapper extends the Mapper Class. The class expects four parameters. The first two parameters are the input key-value pair type and the next two are the intermediate output key-value pair type. Also we override the default map implementation, because the default map function is an identity function.
In the program, we convert each line (value) to string and break it into words. And then for each word we send an intermediate key-value pair of the form (word, 1) to the next phase.
The intermediate key-value pairs now to the shuffle and sort phase where all the pairs with same key are grouped under one key and the values are put in the list. In our case, we get all the key-value pairs in (word, 1) form. So in shuffle & sort phase, we will get (word1, [1, 1, …]), (word2, [1, …]) and so on.
The intermediate key-value pairs now to the shuffle and sort phase where all the pairs with same key are grouped under one key and the values are put in the list. In our case, we get all the key-value pairs in (word, 1) form. So in shuffle & sort phase, we will get (word1, [1, 1, …]), (word2, [1, …]) and so on.
Another thing to note here is that Hadoop has its own basic data types such as Text (for String) and IntWritable (for int). Hadoop provides these data types for optimized serilization.
Step 4: Code the Reducer – The Reducer will take the intermediate key-value pair as input. And for each key-value pair the reduce funtion will be executed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
| import java.io.IOException;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 public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { //Initializing the word count to 0 for every key int count=0; for(IntWritable value: values) { //Adding the word count counter to count count += value.get(); } //Finally write the word and its count context.write(key, new IntWritable(count)); }} |
In the overridden reduce function, we add all the 1’s for every key(word). And for every word, we output the word itself and its count.
Step 5: Code the Driver – We need code to manage the MapReduce job. We call it the driver. The task of the driver is to configure the Job. Job defines the way in which MapReduce is run.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
| 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;public class WordCount { public static void main(String args[]) throws Exception { //Check the correctness of the entered command if(args.length != 2) { System.err.println("Inavlid Command!"); System.err.println("Usage: WordCount <input path> <output path>"); System.exit(0); } //Instantiate the job object for configuring your job Job job = new Job(); //Specify the class that hadoop needs to look in the JAR file //This Jar file is then sent to all the machines in the cluster job.setJarByClass(WordCount.class); //Set a meaningful name to the job job.setJobName("Word Count"); //Add the apth from where the file input is to be taken FileInputFormat.addInputPath(job, new Path(args[0])); //Set the path where the output must be stored FileOutputFormat.setOutputPath(job, new Path(args[1])); //Set the Mapper and the Reducer class job.setMapperClass(WordCountMapper.class); job.setReducerClass(WordCountReducer.class); //Set the type of the key and value of Mapper and reducer /* * If the Mapper output type and Reducer output type are not the same then * also include setMapOutputKeyClass() and setMapOutputKeyValue() */ job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); //Start the job and wait for it to finish. And exit the program based on //the success of the program System.exit(job.waitForCompletion(true)?0:1); }} |
As you see, we instantiate the Job object and specify the following:
- Class which will be called to run the job
- Input directory
- Location where the output should get stored
- Mapper and Reduce class
- Type information of the output key-value pairs of Mapper and Reducer
On successful completion, we exit the code.
Step 6: Run the code – To run the MapReduce job, you must have the input files in the HDFS.
The command to the run the Hadoop Job is as follows:
$:~ hadoop jar <jar_filename.jar> <driver_classname> <input_path> <output_path>
You will get the output similar to the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
| hadoop jar wordCount.jar WordCount input/les_miserables wordCount13/08/20 17:07:49 WARN mapred.JobClient: Use GenericOptionsParser for parsing the arguments. Applications should implement Tool for the same.13/08/20 17:07:49 INFO input.FileInputFormat: Total input paths to process : 113/08/20 17:07:50 INFO mapred.JobClient: Running job: job_201308201538_000213/08/20 17:07:51 INFO mapred.JobClient: map 0% reduce 0%13/08/20 17:08:04 INFO mapred.JobClient: map 100% reduce 0%13/08/20 17:08:13 INFO mapred.JobClient: map 100% reduce 100%13/08/20 17:08:15 INFO mapred.JobClient: Job complete: job_201308201538_000213/08/20 17:08:15 INFO mapred.JobClient: Counters: 3213/08/20 17:08:15 INFO mapred.JobClient: File System Counters13/08/20 17:08:15 INFO mapred.JobClient: FILE: Number of bytes read=128422813/08/20 17:08:15 INFO mapred.JobClient: FILE: Number of bytes written=212638913/08/20 17:08:15 INFO mapred.JobClient: FILE: Number of read operations=013/08/20 17:08:15 INFO mapred.JobClient: FILE: Number of large read operations=013/08/20 17:08:15 INFO mapred.JobClient: FILE: Number of write operations=013/08/20 17:08:15 INFO mapred.JobClient: HDFS: Number of bytes read=332279913/08/20 17:08:15 INFO mapred.JobClient: HDFS: Number of bytes written=28117813/08/20 17:08:15 INFO mapred.JobClient: HDFS: Number of read operations=213/08/20 17:08:15 INFO mapred.JobClient: HDFS: Number of large read operations=013/08/20 17:08:15 INFO mapred.JobClient: HDFS: Number of write operations=113/08/20 17:08:15 INFO mapred.JobClient: Job Counters13/08/20 17:08:15 INFO mapred.JobClient: Launched map tasks=113/08/20 17:08:15 INFO mapred.JobClient: Launched reduce tasks=113/08/20 17:08:15 INFO mapred.JobClient: Data-local map tasks=113/08/20 17:08:15 INFO mapred.JobClient: Total time spent by all maps in occupied slots (ms)=1410513/08/20 17:08:15 INFO mapred.JobClient: Total time spent by all reduces in occupied slots (ms)=760013/08/20 17:08:15 INFO mapred.JobClient: Total time spent by all maps waiting after reserving slots (ms)=013/08/20 17:08:15 INFO mapred.JobClient: Total time spent by all reduces waiting after reserving slots (ms)=013/08/20 17:08:15 INFO mapred.JobClient: Map-Reduce Framework13/08/20 17:08:15 INFO mapred.JobClient: Map input records=6811613/08/20 17:08:15 INFO mapred.JobClient: Map output records=57759913/08/20 17:08:15 INFO mapred.JobClient: Map output bytes=542297113/08/20 17:08:15 INFO mapred.JobClient: Input split bytes=15213/08/20 17:08:15 INFO mapred.JobClient: Combine input records=013/08/20 17:08:15 INFO mapred.JobClient: Combine output records=013/08/20 17:08:15 INFO mapred.JobClient: Reduce input groups=2676313/08/20 17:08:15 INFO mapred.JobClient: Reduce shuffle bytes=52407613/08/20 17:08:15 INFO mapred.JobClient: Reduce input records=57759913/08/20 17:08:15 INFO mapred.JobClient: Reduce output records=2676313/08/20 17:08:15 INFO mapred.JobClient: Spilled Records=173279713/08/20 17:08:15 INFO mapred.JobClient: CPU time spent (ms)=484013/08/20 17:08:15 INFO mapred.JobClient: Physical memory (bytes) snapshot=28925952013/08/20 17:08:15 INFO mapred.JobClient: Virtual memory (bytes) snapshot=141056819213/08/20 17:08:15 INFO mapred.JobClient: Total committed heap usage (bytes)= |
Step 7: View the output – In the output directory you will see _logs, _SUCCESS and part-r-00000. The output gets stored in part-r-00000 file.
1
2
3
4
5
6
7
8
9
10
11
12
| [cloudera@localhost ~]$ hadoop fs -cat wordCount/part-r-00000000 71 7610 6100 4105th 21098 110th 711 31140 11148 1.... |
You can also copy the output to your local disk. To do so, execute the command:
1
| [cloudera@localhost ~]$ hadoop fs -get wordCount ~/Desktop |

No comments:
Post a Comment