all repos — gemini-redirect @ 920dbf76a2de03bdf23db741d4ca79433c7e3b7e

blog/mdad/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 class=left><li><a href=/>lonami's site</a><li><a href=/blog class=selected>blog</a><li><a href=/golb>golb</a></ul><div class=right><a href=https://github.com/LonamiWebs><img src=/img/github.svg alt=github></a><a href=/blog/atom.xml><img src=/img/rss.svg alt=rss></a></div></nav><main><h1 class=title>A practical example with Hadoop</h1><div class=time><p>2020-03-30T01:00:00+00:00<p>last updated 2020-04-18T13:25:43+00:00</div><p>In our <a href=/blog/mdad/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 reproduce the example on Chapter 2 of the book <a href=http://www.hadoopbook.com/>Hadoop: The Definitive Guide, Fourth Edition</a> (<a href=http://grut-computing.com/HadoopBook.pdf>pdf,</a><a href=http://www.hadoopbook.com/code.html>code</a>), that is, finding the maximum global-wide temperature for a given year.<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://apache.brunneis.com/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><p>We will be using the two example data files that they provide in <a href=https://github.com/tomwhite/hadoop-book/tree/master/input/ncdc/all>their GitHub repository</a>, although the full dataset is offered by the <a href=https://www.ncdc.noaa.gov/>National Climatic Data Center</a> (NCDC).<p>We will also unzip and concatenate both files into a single text file, to make it easier to work with. As a single command pipeline:<pre><code>curl https://raw.githubusercontent.com/tomwhite/hadoop-book/master/input/ncdc/all/190{1,2}.gz | gunzip > 190x
 5</code></pre><p>This should create a <code>190x</code> text file in the current directory, which will be our input data.<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 extract the year and air temperature, which will prepare the data for later use (finding the maximum temperature for each year). We will also drop bad records here (if the temperature is missing, suspect or erroneous).<p>Copy or reproduce the following code in a file called <code>MaxTempMapper.java</code>, using any text editor of your choice:<pre><code>import java.io.IOException;
 6
 7import org.apache.hadoop.io.IntWritable;
 8import org.apache.hadoop.io.LongWritable;
 9import org.apache.hadoop.io.Text;
10import org.apache.hadoop.mapreduce.Mapper;
11
12public class MaxTempMapper extends Mapper&LTLongWritable, Text, Text, IntWritable> {
13    private static final int TEMP_MISSING = 9999;
14    private static final String GOOD_QUALITY_RE = "[01459]";
15
16    @Override
17    public void map(LongWritable key, Text value, Context context)
18            throws IOException, InterruptedException {
19        String line = value.toString();
20        String year = line.substring(15, 19);
21        String temp = line.substring(87, 92).replaceAll("^\\+", "");
22        String quality = line.substring(92, 93);
23
24        int airTemperature = Integer.parseInt(temp);
25        if (airTemperature != TEMP_MISSING && quality.matches(GOOD_QUALITY_RE)) {
26            context.write(new Text(year), new IntWritable(airTemperature));
27        }
28    }
29}
30</code></pre><p>Now, let’s create the <code>MaxTempReducer.java</code> file. Its job is to reduce the data from multiple values into just one. We do that by keeping the maximum out of all the values we receive:<pre><code>import java.io.IOException;
31import java.util.Iterator;
32
33import org.apache.hadoop.io.IntWritable;
34import org.apache.hadoop.io.Text;
35import org.apache.hadoop.mapreduce.Reducer;
36
37public class MaxTempReducer extends Reducer&LTText, IntWritable, Text, IntWritable> {
38    @Override
39    public void reduce(Text key, Iterable&LTIntWritable> values, Context context)
40            throws IOException, InterruptedException {
41        Iterator&LTIntWritable> iter = values.iterator();
42        if (iter.hasNext()) {
43            int maxValue = iter.next().get();
44            while (iter.hasNext()) {
45                maxValue = Math.max(maxValue, iter.next().get());
46            }
47            context.write(key, new IntWritable(maxValue));
48        }
49    }
50}
51</code></pre><p>Except for some Java weirdness (…why can’t we just iterate over an <code>Iterator</code>? Or why can’t we just manually call <code>next()</code> on an <code>Iterable</code>?), our code is correct. There can’t be a maximum if there are no elements, and we want to avoid dummy values such as <code>Integer.MIN_VALUE</code>.<p>We can also 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>MaxTemp.java</code>:<pre><code>import org.apache.hadoop.fs.Path;
52import org.apache.hadoop.io.IntWritable;
53import org.apache.hadoop.io.Text;
54import org.apache.hadoop.mapreduce.Job;
55import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
56import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
57
58public class MaxTemp {
59    public static void main(String[] args) throws Exception {
60        if (args.length != 2) {
61            System.err.println("usage: java MaxTemp &LTinput path> &LToutput path>");
62            System.exit(-1);
63        }
64
65        Job job = Job.getInstance();
66
67        job.setJobName("Max temperature");
68        job.setJarByClass(MaxTemp.class);
69        job.setMapperClass(MaxTempMapper.class);
70        job.setReducerClass(MaxTempReducer.class);
71        job.setOutputKeyClass(Text.class);
72        job.setOutputValueClass(IntWritable.class);
73
74        FileInputFormat.addInputPath(job, new Path(args[0]));
75        FileOutputFormat.setOutputPath(job, new Path(args[1]));
76
77        boolean result = job.waitForCompletion(true);
78
79        System.exit(result ? 0 : 1);
80    }
81}
82</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
83</code></pre><p>At last, we can run it (also specifying the dependencies in the classpath, this one’s a mouthful):<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/*" MaxTemp 190x results
84</code></pre><p>Hooray! We should have a new <code>results/</code> folder along with the following files:<pre><code>$ ls results
85part-r-00000  _SUCCESS
86$ cat results/part-r-00000
871901	317
881902	244
89</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!