blog/ribw/a-practical-example-with-hadoop/index.html (view raw)
1<!DOCTYPE html><html lang=en><head><meta charset=utf-8><meta name=description content="Official Lonami's website"><meta name=viewport content="width=device-width, initial-scale=1.0, user-scalable=yes"><title> A practical example with Hadoop | Lonami's Blog </title><link rel=stylesheet href=/style.css><body><article><nav class=sections><ul><li><a href=/>lonami's site</a><li><a href=/blog class=selected>blog</a><li><a href=/golb>golb</a></ul></nav><main><h1 class=title>A practical example with Hadoop</h1><div class=time><p>2020-04-01T02:00:00+00:00<p>last updated 2020-04-03T08:43:41+00:00</div><p>In our <a href=/blog/ribw/introduction-to-hadoop-and-its-mapreduce/>previous Hadoop post</a>, we learnt what it is, how it originated, and how it works, from a theoretical standpoint. Here we will instead focus on a more practical example with Hadoop.<p>This post will showcase my own implementation to implement a word counter for any plain text document that you want to analyze.<h2 id=installation>Installation</h2><p>Before running any piece of software, its executable code must first be downloaded into our computers so that we can run it. Head over to <a href=http://hadoop.apache.org/releases.html>Apache Hadoop’s releases</a> and download the <a href=https://www.apache.org/dyn/closer.cgi/hadoop/common/hadoop-3.2.1/hadoop-3.2.1.tar.gz>latest binary version</a> at the time of writing (3.2.1).<p>We will be using the <a href=https://linuxmint.com/>Linux Mint</a> distribution because I love its simplicity, although the process shown here should work just fine on any similar Linux distribution such as <a href=https://ubuntu.com/>Ubuntu</a>.<p>Once the archive download is complete, extract it with any tool of your choice (graphical or using the terminal) and execute it. Make sure you have a version of Java installed, such as <a href=https://openjdk.java.net/>OpenJDK</a>.<p>Here are all the three steps in the command line:<pre><code>wget https://www.apache.org/dyn/closer.cgi/hadoop/common/hadoop-3.2.1/hadoop-3.2.1.tar.gz
2tar xf hadoop-3.2.1.tar.gz
3hadoop-3.2.1/bin/hadoop version
4</code></pre><h2 id=processing-data>Processing data</h2><p>To take advantage of Hadoop, we have to design our code to work in the MapReduce model. Both the map and reduce phase work on key-value pairs as input and output, and both have a programmer-defined function.<p>We will use Java, because it’s a dependency that we already have anyway, so might as well.<p>Our map function needs to split each of the lines we receive as input into words, and we will also convert them to lowercase, thus preparing the data for later use (counting words). There won’t be bad records, so we don’t have to worry about that.<p>Copy or reproduce the following code in a file called <code>WordCountMapper.java</code>, using any text editor of your choice:<pre><code>import java.io.IOException;
5
6import org.apache.hadoop.io.IntWritable;
7import org.apache.hadoop.io.LongWritable;
8import org.apache.hadoop.io.Text;
9import org.apache.hadoop.mapreduce.Mapper;
10
11public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
12 @Override
13 public void map(LongWritable key, Text value, Context context)
14 throws IOException, InterruptedException {
15 for (String word : value.toString().split("\\W")) {
16 context.write(new Text(word.toLowerCase()), new IntWritable(1));
17 }
18 }
19}
20</code></pre><p>Now, let’s create the <code>WordCountReducer.java</code> file. Its job is to reduce the data from multiple values into just one. We do that by summing all the values (our word count so far):<pre><code>import java.io.IOException;
21import java.util.Iterator;
22
23import org.apache.hadoop.io.IntWritable;
24import org.apache.hadoop.io.Text;
25import org.apache.hadoop.mapreduce.Reducer;
26
27public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
28 @Override
29 public void reduce(Text key, Iterable<IntWritable> values, Context context)
30 throws IOException, InterruptedException {
31 int count = 0;
32 for (IntWritable value : values) {
33 count += value.get();
34 }
35 context.write(key, new IntWritable(count));
36 }
37}
38</code></pre><p>Let’s just take a moment to appreciate how absolutely tiny this code is, and it’s Java! Hadoop’s API is really awesome and lets us write such concise code to achieve what we need.<p>Last, let’s write the <code>main</code> method, or else we won’t be able to run it. In our new file <code>WordCount.java</code>:<pre><code>import org.apache.hadoop.fs.Path;
39import org.apache.hadoop.io.IntWritable;
40import org.apache.hadoop.io.Text;
41import org.apache.hadoop.mapreduce.Job;
42import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
43import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
44
45public class WordCount {
46 public static void main(String[] args) throws Exception {
47 if (args.length != 2) {
48 System.err.println("usage: java WordCount <input path> <output path>");
49 System.exit(-1);
50 }
51
52 Job job = Job.getInstance();
53
54 job.setJobName("Word count");
55 job.setJarByClass(WordCount.class);
56 job.setMapperClass(WordCountMapper.class);
57 job.setReducerClass(WordCountReducer.class);
58 job.setOutputKeyClass(Text.class);
59 job.setOutputValueClass(IntWritable.class);
60
61 FileInputFormat.addInputPath(job, new Path(args[0]));
62 FileOutputFormat.setOutputPath(job, new Path(args[1]));
63
64 boolean result = job.waitForCompletion(true);
65
66 System.exit(result ? 0 : 1);
67 }
68}
69</code></pre><p>And compile by including the required <code>.jar</code> dependencies in Java’s classpath with the <code>-cp</code> switch:<pre><code>javac -cp "hadoop-3.2.1/share/hadoop/common/*:hadoop-3.2.1/share/hadoop/mapreduce/*" *.java
70</code></pre><p>At last, we can run it (also specifying the dependencies in the classpath, this one’s a mouthful). Let’s run it on the same <code>WordCount.java</code> source file we wrote:<pre><code>java -cp ".:hadoop-3.2.1/share/hadoop/common/*:hadoop-3.2.1/share/hadoop/common/lib/*:hadoop-3.2.1/share/hadoop/mapreduce/*:hadoop-3.2.1/share/hadoop/mapreduce/lib/*:hadoop-3.2.1/share/hadoop/yarn/*:hadoop-3.2.1/share/hadoop/yarn/lib/*:hadoop-3.2.1/share/hadoop/hdfs/*:hadoop-3.2.1/share/hadoop/hdfs/lib/*" WordCount WordCount.java results
71</code></pre><p>Hooray! We should have a new <code>results/</code> folder along with the following files:<pre><code>$ ls results
72part-r-00000 _SUCCESS
73$ cat results/part-r-00000
74 154
750 2
761 3
772 1
78addinputpath 1
79apache 6
80args 4
81boolean 1
82class 6
83count 1
84err 1
85exception 1
86-snip- (output cut for clarity)
87</code></pre><p>It worked! Now this example was obviously tiny, but hopefully enough to demonstrate how to get the basics running on real world data.</main><footer><div><p>Share your thoughts, or simply come hang with me <a href=https://t.me/LonamiWebs><img src=/img/telegram.svg alt=Telegram></a> <a href=mailto:totufals@hotmail.com><img src=/img/mail.svg alt=Mail></a></div></footer></article><p class=abyss>Glaze into the abyss… Oh hi there!