Debian Codegraph @

doc/content/en/docs/1.11.2/MapReduce guide/_index.md

raw
1 ---
2 title: "MapReduce guide"
3 linkTitle: "MapReduce guide"
4 weight: 200
5 ---
6
7 <!--
8
9 Licensed to the Apache Software Foundation (ASF) under one
10 or more contributor license agreements. See the NOTICE file
11 distributed with this work for additional information
12 regarding copyright ownership. The ASF licenses this file
13 to you under the Apache License, Version 2.0 (the
14 "License"); you may not use this file except in compliance
15 with the License. You may obtain a copy of the License at
16
17 https://www.apache.org/licenses/LICENSE-2.0
18
19 Unless required by applicable law or agreed to in writing,
20 software distributed under the License is distributed on an
21 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
22 KIND, either express or implied. See the License for the
23 specific language governing permissions and limitations
24 under the License.
25
26 -->
27
28 Avro provides a convenient way to represent complex data structures within a Hadoop MapReduce job. Avro data can be used as both input to and output from a MapReduce job, as well as the intermediate format. The example in this guide uses Avro data for all three, but it's possible to mix and match; for instance, MapReduce can be used to aggregate a particular field in an Avro record.
29
30 This guide assumes basic familiarity with both Hadoop MapReduce and Avro. See the [Hadoop documentation](https://hadoop.apache.org/docs/current/) and the [Avro getting started guide](./getting-started-java/) for introductions to these projects. This guide uses the old MapReduce API (`org.apache.hadoop.mapred`) and the new MapReduce API (`org.apache.hadoop.mapreduce`).
31
32 ## Setup
33 The code from this guide is included in the Avro docs under examples/mr-example. The example is set up as a Maven project that includes the necessary Avro and MapReduce dependencies and the Avro Maven plugin for code generation, so no external jars are needed to run the example. In particular, the POM includes the following dependencies:
34 ```xml
35 <dependency>
36 <groupId>org.apache.avro</groupId>
37 <artifactId>avro</artifactId>
38 <version>1.11.2</version>
39 </dependency>
40 <dependency>
41 <groupId>org.apache.avro</groupId>
42 <artifactId>avro-mapred</artifactId>
43 <version>1.11.2</version>
44 </dependency>
45 <dependency>
46 <groupId>org.apache.hadoop</groupId>
47 <artifactId>hadoop-client</artifactId>
48 <version>3.1.2</version>
49 </dependency>
50 ```
51 And the following plugin:
52 ```xml
53 <plugin>
54 <groupId>org.apache.avro</groupId>
55 <artifactId>avro-maven-plugin</artifactId>
56 <version>1.11.2</version>
57 <executions>
58 <execution>
59 <phase>generate-sources</phase>
60 <goals>
61 <goal>schema</goal>
62 </goals>
63 <configuration>
64 <sourceDirectory>${project.basedir}/../</sourceDirectory>
65 <outputDirectory>${project.basedir}/target/generated-sources/</outputDirectory>
66 </configuration>
67 </execution>
68 </executions>
69 </plugin>
70 ```
71
72 If you do not configure the *sourceDirectory* and *outputDirectory* properties, the defaults will be used. The *sourceDirectory* property defaults to *src/main/avro*. The *outputDirectory* property defaults to *target/generated-sources*. You can change the paths to match your project layout.
73
74 Alternatively, Avro jars can be downloaded directly from the Apache Avro™ Releases [page](https://avro.apache.org/releases.html). The relevant Avro jars for this guide are *avro-1.11.2.jar* and *avro-mapred-1.11.2.jar*, as well as *avro-tools-1.11.2.jar* for code generation and viewing Avro data files as JSON. In addition, you will need to install Hadoop in order to use MapReduce.
75
76 ## Example: ColorCount
77 Below is a simple example of a MapReduce that uses Avro. There is an example for both the old (org.apache.hadoop.mapred) and new (org.apache.hadoop.mapreduce) APIs under *examples/mr-example/src/main/java/example/*. _MapredColorCount_ is the example for the older mapred API while _MapReduceColorCount_ is the example for the newer mapreduce API. Both examples are below, but we will detail the mapred API in our subsequent examples.
78
79 MapredColorCount.java:
80 ```java
81 package example;
82
83 import java.io.IOException;
84
85 import org.apache.avro.*;
86 import org.apache.avro.Schema.Type;
87 import org.apache.avro.mapred.*;
88 import org.apache.hadoop.conf.*;
89 import org.apache.hadoop.fs.Path;
90 import org.apache.hadoop.mapred.*;
91 import org.apache.hadoop.util.*;
92
93 import example.avro.User;
94
95 public class MapredColorCount extends Configured implements Tool {
96
97 public static class ColorCountMapper extends AvroMapper<User, Pair<CharSequence, Integer>> {
98 @Override
99 public void map(User user, AvroCollector<Pair<CharSequence, Integer>> collector, Reporter reporter)
100 throws IOException {
101 CharSequence color = user.getFavoriteColor();
102 // We need this check because the User.favorite_color field has type ["string", "null"]
103 if (color == null) {
104 color = "none";
105 }
106 collector.collect(new Pair<CharSequence, Integer>(color, 1));
107 }
108 }
109
110 public static class ColorCountReducer extends AvroReducer<CharSequence, Integer,
111 Pair<CharSequence, Integer>> {
112 @Override
113 public void reduce(CharSequence key, Iterable<Integer> values,
114 AvroCollector<Pair<CharSequence, Integer>> collector,
115 Reporter reporter)
116 throws IOException {
117 int sum = 0;
118 for (Integer value : values) {
119 sum += value;
120 }
121 collector.collect(new Pair<CharSequence, Integer>(key, sum));
122 }
123 }
124
125 public int run(String[] args) throws Exception {
126 if (args.length != 2) {
127 System.err.println("Usage: MapredColorCount <input path> <output path>");
128 return -1;
129 }
130
131 JobConf conf = new JobConf(getConf(), MapredColorCount.class);
132 conf.setJobName("colorcount");
133
134 FileInputFormat.setInputPaths(conf, new Path(args[0]));
135 FileOutputFormat.setOutputPath(conf, new Path(args[1]));
136
137 AvroJob.setMapperClass(conf, ColorCountMapper.class);
138 AvroJob.setReducerClass(conf, ColorCountReducer.class);
139
140 // Note that AvroJob.setInputSchema and AvroJob.setOutputSchema set
141 // relevant config options such as input/output format, map output
142 // classes, and output key class.
143 AvroJob.setInputSchema(conf, User.getClassSchema());
144 AvroJob.setOutputSchema(conf, Pair.getPairSchema(Schema.create(Type.STRING),
145 Schema.create(Type.INT)));
146
147 JobClient.runJob(conf);
148 return 0;
149 }
150
151 public static void main(String[] args) throws Exception {
152 int res = ToolRunner.run(new Configuration(), new MapredColorCount(), args);
153 System.exit(res);
154 }
155 }
156 ```
157
158 MapReduceColorCount.java:
159 ```java
160 package example;
161
162 import java.io.IOException;
163
164 import org.apache.avro.Schema;
165 import org.apache.avro.mapred.AvroKey;
166 import org.apache.avro.mapred.AvroValue;
167 import org.apache.avro.mapreduce.AvroJob;
168 import org.apache.avro.mapreduce.AvroKeyInputFormat;
169 import org.apache.avro.mapreduce.AvroKeyValueOutputFormat;
170 import org.apache.hadoop.conf.Configured;
171 import org.apache.hadoop.fs.Path;
172 import org.apache.hadoop.io.IntWritable;
173 import org.apache.hadoop.io.NullWritable;
174 import org.apache.hadoop.io.Text;
175 import org.apache.hadoop.mapreduce.Job;
176 import org.apache.hadoop.mapreduce.Mapper;
177 import org.apache.hadoop.mapreduce.Reducer;
178 import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
179 import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
180 import org.apache.hadoop.util.Tool;
181 import org.apache.hadoop.util.ToolRunner;
182
183 import example.avro.User;
184
185 public class MapReduceColorCount extends Configured implements Tool {
186
187 public static class ColorCountMapper extends
188 Mapper<AvroKey<User>, NullWritable, Text, IntWritable> {
189
190 @Override
191 public void map(AvroKey<User> key, NullWritable value, Context context)
192 throws IOException, InterruptedException {
193
194 CharSequence color = key.datum().getFavoriteColor();
195 if (color == null) {
196 color = "none";
197 }
198 context.write(new Text(color.toString()), new IntWritable(1));
199 }
200 }
201
202 public static class ColorCountReducer extends
203 Reducer<Text, IntWritable, AvroKey<CharSequence>, AvroValue<Integer>> {
204
205 @Override
206 public void reduce(Text key, Iterable<IntWritable> values,
207 Context context) throws IOException, InterruptedException {
208
209 int sum = 0;
210 for (IntWritable value : values) {
211 sum += value.get();
212 }
213 context.write(new AvroKey<CharSequence>(key.toString()), new AvroValue<Integer>(sum));
214 }
215 }
216
217 public int run(String[] args) throws Exception {
218 if (args.length != 2) {
219 System.err.println("Usage: MapReduceColorCount <input path> <output path>");
220 return -1;
221 }
222
223 Job job = new Job(getConf());
224 job.setJarByClass(MapReduceColorCount.class);
225 job.setJobName("Color Count");
226
227 FileInputFormat.setInputPaths(job, new Path(args[0]));
228 FileOutputFormat.setOutputPath(job, new Path(args[1]));
229
230 job.setInputFormatClass(AvroKeyInputFormat.class);
231 job.setMapperClass(ColorCountMapper.class);
232 AvroJob.setInputKeySchema(job, User.getClassSchema());
233 job.setMapOutputKeyClass(Text.class);
234 job.setMapOutputValueClass(IntWritable.class);
235
236 job.setOutputFormatClass(AvroKeyValueOutputFormat.class);
237 job.setReducerClass(ColorCountReducer.class);
238 AvroJob.setOutputKeySchema(job, Schema.create(Schema.Type.STRING));
239 AvroJob.setOutputValueSchema(job, Schema.create(Schema.Type.INT));
240
241 return (job.waitForCompletion(true) ? 0 : 1);
242 }
243
244 public static void main(String[] args) throws Exception {
245 int res = ToolRunner.run(new MapReduceColorCount(), args);
246 System.exit(res);
247 }
248 }
249 ```
250 ColorCount reads in data files containing *User* records, defined in _examples/user.avsc_, and counts the number of instances of each favorite color. (This example draws inspiration from the canonical _WordCount_ MapReduce application.) This example uses the old MapReduce API. See MapReduceAvroWordCount, found under _doc/examples/mr-example/src/main/java/example/_ to see the new MapReduce API example. The User schema is defined as follows:
251 ```json
252 {"namespace": "example.avro",
253 "type": "record",
254 "name": "User",
255 "fields": [
256 {"name": "name", "type": "string"},
257 {"name": "favorite_number", "type": ["int", "null"]},
258 {"name": "favorite_color", "type": ["string", "null"]}
259 ]
260 }
261 ```
262 This schema is compiled into the *User* class used by *ColorCount* via the Avro Maven plugin (see _examples/mr-example/pom.xml_ for how this is set up).
263
264 *ColorCountMapper* essentially takes a *User* as input and extracts the User's favorite color, emitting the key-value pair `<favoriteColor, 1>`. _ColorCountReducer_ then adds up how many occurrences of a particular favorite color were emitted, and outputs the result as a Pair record. These Pairs are serialized to an Avro data file.
265
266 ## Running ColorCount
267 The _ColorCount_ application is provided as a Maven project in the Avro docs under _examples/mr-example_. To build the project, including the code generation of the User schema, run:
268 ```shell
269 mvn compile
270 ```
271 Next, run _GenerateData_ from `examples/mr-examples` to create an Avro data file, `input/users.avro`, containing 20 Users with favorite colors chosen randomly from a list:
272 ```shell
273 mvn exec:java -q -Dexec.mainClass=example.GenerateData
274 ```
275 Besides creating the data file, GenerateData prints the JSON representations of the Users generated to stdout, for example:
276 ```json
277 {"name": "user", "favorite_number": null, "favorite_color": "red"}
278 {"name": "user", "favorite_number": null, "favorite_color": "green"}
279 {"name": "user", "favorite_number": null, "favorite_color": "purple"}
280 {"name": "user", "favorite_number": null, "favorite_color": null}
281 ...
282 ```
283 Now we're ready to run ColorCount. We specify our freshly-generated input folder as the input path and output as our output folder (note that MapReduce will not start a job if the output folder already exists):
284 ```shell
285 mvn exec:java -q -Dexec.mainClass=example.MapredColorCount -Dexec.args="input output"
286 ```
287 Once ColorCount completes, checking the contents of the new output directory should yield the following:
288 ```shell
289 $ ls output/
290 part-00000.avro _SUCCESS
291 ```
292 You can check the contents of the generated Avro file using the avro-tools jar:
293 ```shell
294 $ java -jar /path/to/avro-tools-1.11.2.jar tojson output/part-00000.avro
295 {"value": 3, "key": "blue"}
296 {"value": 7, "key": "green"}
297 {"value": 1, "key": "none"}
298 {"value": 2, "key": "orange"}
299 {"value": 3, "key": "purple"}
300 {"value": 2, "key": "red"}
301 {"value": 2, "key": "yellow"}
302 ```
303 Now let's go over the ColorCount example in detail.
304
305 ## AvroMapper - org.apache.hadoop.mapred API
306
307 The easiest way to use Avro data files as input to a MapReduce job is to subclass `AvroMapper`. An `AvroMapper` defines a `map` function that takes an Avro datum as input and outputs a key/value pair represented as a Pair record. In the ColorCount example, ColorCountMapper is an AvroMapper that takes a User as input and outputs a `Pair<CharSequence, Integer>>`, where the CharSequence key is the user's favorite color and the Integer value is 1.
308 ```java
309 public static class ColorCountMapper extends AvroMapper<User, Pair<CharSequence, Integer>> {
310 @Override
311 public void map(User user, AvroCollector<Pair<CharSequence, Integer>> collector, Reporter reporter)
312 throws IOException {
313 CharSequence color = user.getFavoriteColor();
314 // We need this check because the User.favorite_color field has type ["string", "null"]
315 if (color == null) {
316 color = "none";
317 }
318 collector.collect(new Pair<CharSequence, Integer>(color, 1));
319 }
320 }
321 ```
322 In order to use our AvroMapper, we must call AvroJob.setMapperClass and AvroJob.setInputSchema.
323 ```java
324 AvroJob.setMapperClass(conf, ColorCountMapper.class);
325 AvroJob.setInputSchema(conf, User.getClassSchema());
326 ```
327 Note that `AvroMapper` does not implement the `Mapper` interface. Under the hood, the specified Avro data files are deserialized into AvroWrappers containing the actual data, which are processed by a Mapper that calls the configured AvroMapper's map function. AvroJob.setInputSchema sets up the relevant configuration parameters needed to make this happen, thus you should not need to call `JobConf.setMapperClass`, `JobConf.setInputFormat`, `JobConf.setMapOutputKeyClass`, `JobConf.setMapOutputValueClass`, or `JobConf.setOutputKeyComparatorClass`.
328
329 ## Mapper - org.apache.hadoop.mapreduce API
330 This document will not go into all the differences between the mapred and mapreduce APIs, however will describe the main differences. As you can see, ColorCountMapper is now a subclass of the Hadoop Mapper class and is passed an AvroKey as it's key. Additionally, the AvroJob method calls were slightly changed.
331 ```java
332 public static class ColorCountMapper extends
333 Mapper<AvroKey<User>, NullWritable, Text, IntWritable> {
334
335 @Override
336 public void map(AvroKey<User> key, NullWritable value, Context context)
337 throws IOException, InterruptedException {
338
339 CharSequence color = key.datum().getFavoriteColor();
340 if (color == null) {
341 color = "none";
342 }
343 context.write(new Text(color.toString()), new IntWritable(1));
344 }
345 }
346 ```
347
348 ## AvroReducer - org.apache.hadoop.mapred API
349 Analogously to AvroMapper, an AvroReducer defines a reducer function that takes the key/value types output by an AvroMapper (or any mapper that outputs Pairs) and outputs a key/value pair represented a Pair record. In the ColorCount example, ColorCountReducer is an AvroReducer that takes the CharSequence key representing a favorite color and the `Iterable<Integer>` representing the counts for that color (they should all be 1 in this example) and adds up the counts.
350 ```java
351 public static class ColorCountReducer extends AvroReducer<CharSequence, Integer,
352 Pair<CharSequence, Integer>> {
353 @Override
354 public void reduce(CharSequence key, Iterable<Integer> values,
355 AvroCollector<Pair<CharSequence, Integer>> collector,
356 Reporter reporter)
357 throws IOException {
358 int sum = 0;
359 for (Integer value : values) {
360 sum += value;
361 }
362 collector.collect(new Pair<CharSequence, Integer>(key, sum));
363 }
364 }
365 ```
366 In order to use our AvroReducer, we must call AvroJob.setReducerClass and AvroJob.setOutputSchema.
367 ```java
368 AvroJob.setReducerClass(conf, ColorCountReducer.class);
369 AvroJob.setOutputSchema(conf, Pair.getPairSchema(Schema.create(Type.STRING),
370 Schema.create(Type.INT)));
371 ```
372 Note that _AvroReducer_ does not implement the _Reducer_ interface. The intermediate Pairs output by the mapper are split into _AvroKeys_ and _AvroValues_, which are processed by a Reducer that calls the configured AvroReducer's `reduce` function. `AvroJob.setOutputSchema` sets up the relevant configuration parameters needed to make this happen, thus you should not need to call `JobConf.setReducerClass`, `JobConf.setOutputFormat`, `JobConf.setOutputKeyClass`, `JobConf.setMapOutputKeyClass`, `JobConf.setMapOutputValueClass`, or `JobConf.setOutputKeyComparatorClass`.
373
374 ## Reduce - org.apache.hadoop.mapreduce API
375 As before we not detail every difference between the APIs. As with the _Mapper_ change _ColorCountReducer_ is now a subclass of _Reducer_ and _AvroKey_ and _AvroValue_ are emitted. Additionally, the _AvroJob_ method calls were slightly changed.
376 ```java
377 public static class ColorCountReducer extends
378 Reducer<Text, IntWritable, AvroKey<CharSequence>, AvroValue<Integer>> {
379
380 @Override
381 public void reduce(Text key, Iterable<IntWritable> values,
382 Context context) throws IOException, InterruptedException {
383
384 int sum = 0;
385 for (IntWritable value : values) {
386 sum += value.get();
387 }
388 context.write(new AvroKey<CharSequence>(key.toString()), new AvroValue<Integer>(sum));
389 }
390 }
391 ```
392
393 ## Learning more
394 The mapred API allows users to mix Avro AvroMappers and AvroReducers with non-Avro Mappers and Reducers and the mapreduce API allows users input Avro and output non-Avro or vice versa.
395
396 The mapred package has API org.apache.avro.mapred documentation as does the `org.apache.avro.mapreduce` package. MapReduce API (`org.apache.hadoop.mapreduce`). Similarily to the mapreduce package, it's possible with the mapred API to implement your own Mappers and Reducers directly using the public classes provided in these libraries. See the `AvroWordCount` application, found under _examples/mr-example/src/main/java/example/AvroWordCount.java_ in the Avro documentation, for an example of implementing a Reducer that outputs Avro data using the old MapReduce API. See the `MapReduceAvroWordCount` application, found under _examples/mr-example/src/main/java/example/MapReduceAvroWordCount.java_ in the Avro documentation, for an example of implementing a Reducer that outputs Avro data using the new MapReduce API.