Debian Codegraph @

doc/content/en/docs/++version++/MapReduce guide/_index.md

raw
1 ---
2 title: "MapReduce guide"
3 linkTitle: "MapReduce guide"
4 weight: 200
5 aliases:
6 - /docs/current/mapreduce-guide/
7 ---
8
9 <!--
10
11 Licensed to the Apache Software Foundation (ASF) under one
12 or more contributor license agreements. See the NOTICE file
13 distributed with this work for additional information
14 regarding copyright ownership. The ASF licenses this file
15 to you under the Apache License, Version 2.0 (the
16 "License"); you may not use this file except in compliance
17 with the License. You may obtain a copy of the License at
18
19 https://www.apache.org/licenses/LICENSE-2.0
20
21 Unless required by applicable law or agreed to in writing,
22 software distributed under the License is distributed on an
23 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
24 KIND, either express or implied. See the License for the
25 specific language governing permissions and limitations
26 under the License.
27
28 -->
29
30 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.
31
32 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`).
33
34 ## Setup
35 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:
36 ```xml
37 <dependency>
38 <groupId>org.apache.avro</groupId>
39 <artifactId>avro</artifactId>
40 <version>{{< avro_version >}}</version>
41 </dependency>
42 <dependency>
43 <groupId>org.apache.avro</groupId>
44 <artifactId>avro-mapred</artifactId>
45 <version>{{< avro_version >}}</version>
46 </dependency>
47 <dependency>
48 <groupId>org.apache.hadoop</groupId>
49 <artifactId>hadoop-client</artifactId>
50 <version>3.1.2</version>
51 </dependency>
52 ```
53 And the following plugin:
54 ```xml
55 <plugin>
56 <groupId>org.apache.avro</groupId>
57 <artifactId>avro-maven-plugin</artifactId>
58 <version>{{< avro_version >}}</version>
59 <executions>
60 <execution>
61 <phase>generate-sources</phase>
62 <goals>
63 <goal>schema</goal>
64 </goals>
65 <configuration>
66 <sourceDirectory>${project.basedir}/../</sourceDirectory>
67 <outputDirectory>${project.basedir}/target/generated-sources/</outputDirectory>
68 </configuration>
69 </execution>
70 </executions>
71 </plugin>
72 ```
73
74 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.
75
76 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-{{< avro_version >}}.jar* and *avro-mapred-{{< avro_version >}}.jar*, as well as *avro-tools-{{< avro_version >}}.jar* for code generation and viewing Avro data files as JSON. In addition, you will need to install Hadoop in order to use MapReduce.
77
78 ## Example: ColorCount
79 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.
80
81 MapredColorCount.java:
82 ```java
83 package example;
84
85 import java.io.IOException;
86
87 import org.apache.avro.*;
88 import org.apache.avro.Schema.Type;
89 import org.apache.avro.mapred.*;
90 import org.apache.hadoop.conf.*;
91 import org.apache.hadoop.fs.Path;
92 import org.apache.hadoop.mapred.*;
93 import org.apache.hadoop.util.*;
94
95 import example.avro.User;
96
97 public class MapredColorCount extends Configured implements Tool {
98
99 public static class ColorCountMapper extends AvroMapper<User, Pair<CharSequence, Integer>> {
100 @Override
101 public void map(User user, AvroCollector<Pair<CharSequence, Integer>> collector, Reporter reporter)
102 throws IOException {
103 CharSequence color = user.getFavoriteColor();
104 // We need this check because the User.favorite_color field has type ["string", "null"]
105 if (color == null) {
106 color = "none";
107 }
108 collector.collect(new Pair<CharSequence, Integer>(color, 1));
109 }
110 }
111
112 public static class ColorCountReducer extends AvroReducer<CharSequence, Integer,
113 Pair<CharSequence, Integer>> {
114 @Override
115 public void reduce(CharSequence key, Iterable<Integer> values,
116 AvroCollector<Pair<CharSequence, Integer>> collector,
117 Reporter reporter)
118 throws IOException {
119 int sum = 0;
120 for (Integer value : values) {
121 sum += value;
122 }
123 collector.collect(new Pair<CharSequence, Integer>(key, sum));
124 }
125 }
126
127 public int run(String[] args) throws Exception {
128 if (args.length != 2) {
129 System.err.println("Usage: MapredColorCount <input path> <output path>");
130 return -1;
131 }
132
133 JobConf conf = new JobConf(getConf(), MapredColorCount.class);
134 conf.setJobName("colorcount");
135
136 FileInputFormat.setInputPaths(conf, new Path(args[0]));
137 FileOutputFormat.setOutputPath(conf, new Path(args[1]));
138
139 AvroJob.setMapperClass(conf, ColorCountMapper.class);
140 AvroJob.setReducerClass(conf, ColorCountReducer.class);
141
142 // Note that AvroJob.setInputSchema and AvroJob.setOutputSchema set
143 // relevant config options such as input/output format, map output
144 // classes, and output key class.
145 AvroJob.setInputSchema(conf, User.getClassSchema());
146 AvroJob.setOutputSchema(conf, Pair.getPairSchema(Schema.create(Type.STRING),
147 Schema.create(Type.INT)));
148
149 JobClient.runJob(conf);
150 return 0;
151 }
152
153 public static void main(String[] args) throws Exception {
154 int res = ToolRunner.run(new Configuration(), new MapredColorCount(), args);
155 System.exit(res);
156 }
157 }
158 ```
159
160 MapReduceColorCount.java:
161 ```java
162 package example;
163
164 import java.io.IOException;
165
166 import org.apache.avro.Schema;
167 import org.apache.avro.mapred.AvroKey;
168 import org.apache.avro.mapred.AvroValue;
169 import org.apache.avro.mapreduce.AvroJob;
170 import org.apache.avro.mapreduce.AvroKeyInputFormat;
171 import org.apache.avro.mapreduce.AvroKeyValueOutputFormat;
172 import org.apache.hadoop.conf.Configured;
173 import org.apache.hadoop.fs.Path;
174 import org.apache.hadoop.io.IntWritable;
175 import org.apache.hadoop.io.NullWritable;
176 import org.apache.hadoop.io.Text;
177 import org.apache.hadoop.mapreduce.Job;
178 import org.apache.hadoop.mapreduce.Mapper;
179 import org.apache.hadoop.mapreduce.Reducer;
180 import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
181 import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
182 import org.apache.hadoop.util.Tool;
183 import org.apache.hadoop.util.ToolRunner;
184
185 import example.avro.User;
186
187 public class MapReduceColorCount extends Configured implements Tool {
188
189 public static class ColorCountMapper extends
190 Mapper<AvroKey<User>, NullWritable, Text, IntWritable> {
191
192 @Override
193 public void map(AvroKey<User> key, NullWritable value, Context context)
194 throws IOException, InterruptedException {
195
196 CharSequence color = key.datum().getFavoriteColor();
197 if (color == null) {
198 color = "none";
199 }
200 context.write(new Text(color.toString()), new IntWritable(1));
201 }
202 }
203
204 public static class ColorCountReducer extends
205 Reducer<Text, IntWritable, AvroKey<CharSequence>, AvroValue<Integer>> {
206
207 @Override
208 public void reduce(Text key, Iterable<IntWritable> values,
209 Context context) throws IOException, InterruptedException {
210
211 int sum = 0;
212 for (IntWritable value : values) {
213 sum += value.get();
214 }
215 context.write(new AvroKey<CharSequence>(key.toString()), new AvroValue<Integer>(sum));
216 }
217 }
218
219 public int run(String[] args) throws Exception {
220 if (args.length != 2) {
221 System.err.println("Usage: MapReduceColorCount <input path> <output path>");
222 return -1;
223 }
224
225 Job job = new Job(getConf());
226 job.setJarByClass(MapReduceColorCount.class);
227 job.setJobName("Color Count");
228
229 FileInputFormat.setInputPaths(job, new Path(args[0]));
230 FileOutputFormat.setOutputPath(job, new Path(args[1]));
231
232 job.setInputFormatClass(AvroKeyInputFormat.class);
233 job.setMapperClass(ColorCountMapper.class);
234 AvroJob.setInputKeySchema(job, User.getClassSchema());
235 job.setMapOutputKeyClass(Text.class);
236 job.setMapOutputValueClass(IntWritable.class);
237
238 job.setOutputFormatClass(AvroKeyValueOutputFormat.class);
239 job.setReducerClass(ColorCountReducer.class);
240 AvroJob.setOutputKeySchema(job, Schema.create(Schema.Type.STRING));
241 AvroJob.setOutputValueSchema(job, Schema.create(Schema.Type.INT));
242
243 return (job.waitForCompletion(true) ? 0 : 1);
244 }
245
246 public static void main(String[] args) throws Exception {
247 int res = ToolRunner.run(new MapReduceColorCount(), args);
248 System.exit(res);
249 }
250 }
251 ```
252 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:
253 ```json
254 {"namespace": "example.avro",
255 "type": "record",
256 "name": "User",
257 "fields": [
258 {"name": "name", "type": "string"},
259 {"name": "favorite_number", "type": ["int", "null"]},
260 {"name": "favorite_color", "type": ["string", "null"]}
261 ]
262 }
263 ```
264 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).
265
266 *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.
267
268 ## Running ColorCount
269 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:
270 ```shell
271 mvn compile
272 ```
273 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:
274 ```shell
275 mvn exec:java -q -Dexec.mainClass=example.GenerateData
276 ```
277 Besides creating the data file, GenerateData prints the JSON representations of the Users generated to stdout, for example:
278 ```json
279 {"name": "user", "favorite_number": null, "favorite_color": "red"}
280 {"name": "user", "favorite_number": null, "favorite_color": "green"}
281 {"name": "user", "favorite_number": null, "favorite_color": "purple"}
282 {"name": "user", "favorite_number": null, "favorite_color": null}
283 ...
284 ```
285 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):
286 ```shell
287 mvn exec:java -q -Dexec.mainClass=example.MapredColorCount -Dexec.args="input output"
288 ```
289 Once ColorCount completes, checking the contents of the new output directory should yield the following:
290 ```shell
291 $ ls output/
292 part-00000.avro _SUCCESS
293 ```
294 You can check the contents of the generated Avro file using the avro-tools jar:
295 ```shell
296 $ java -jar /path/to/avro-tools-{{< avro_version >}}.jar tojson output/part-00000.avro
297 {"value": 3, "key": "blue"}
298 {"value": 7, "key": "green"}
299 {"value": 1, "key": "none"}
300 {"value": 2, "key": "orange"}
301 {"value": 3, "key": "purple"}
302 {"value": 2, "key": "red"}
303 {"value": 2, "key": "yellow"}
304 ```
305 Now let's go over the ColorCount example in detail.
306
307 ## AvroMapper - org.apache.hadoop.mapred API
308
309 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.
310 ```java
311 public static class ColorCountMapper extends AvroMapper<User, Pair<CharSequence, Integer>> {
312 @Override
313 public void map(User user, AvroCollector<Pair<CharSequence, Integer>> collector, Reporter reporter)
314 throws IOException {
315 CharSequence color = user.getFavoriteColor();
316 // We need this check because the User.favorite_color field has type ["string", "null"]
317 if (color == null) {
318 color = "none";
319 }
320 collector.collect(new Pair<CharSequence, Integer>(color, 1));
321 }
322 }
323 ```
324 In order to use our AvroMapper, we must call AvroJob.setMapperClass and AvroJob.setInputSchema.
325 ```java
326 AvroJob.setMapperClass(conf, ColorCountMapper.class);
327 AvroJob.setInputSchema(conf, User.getClassSchema());
328 ```
329 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`.
330
331 ## Mapper - org.apache.hadoop.mapreduce API
332 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.
333 ```java
334 public static class ColorCountMapper extends
335 Mapper<AvroKey<User>, NullWritable, Text, IntWritable> {
336
337 @Override
338 public void map(AvroKey<User> key, NullWritable value, Context context)
339 throws IOException, InterruptedException {
340
341 CharSequence color = key.datum().getFavoriteColor();
342 if (color == null) {
343 color = "none";
344 }
345 context.write(new Text(color.toString()), new IntWritable(1));
346 }
347 }
348 ```
349
350 ## AvroReducer - org.apache.hadoop.mapred API
351 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.
352 ```java
353 public static class ColorCountReducer extends AvroReducer<CharSequence, Integer,
354 Pair<CharSequence, Integer>> {
355 @Override
356 public void reduce(CharSequence key, Iterable<Integer> values,
357 AvroCollector<Pair<CharSequence, Integer>> collector,
358 Reporter reporter)
359 throws IOException {
360 int sum = 0;
361 for (Integer value : values) {
362 sum += value;
363 }
364 collector.collect(new Pair<CharSequence, Integer>(key, sum));
365 }
366 }
367 ```
368 In order to use our AvroReducer, we must call AvroJob.setReducerClass and AvroJob.setOutputSchema.
369 ```java
370 AvroJob.setReducerClass(conf, ColorCountReducer.class);
371 AvroJob.setOutputSchema(conf, Pair.getPairSchema(Schema.create(Type.STRING),
372 Schema.create(Type.INT)));
373 ```
374 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`.
375
376 ## Reduce - org.apache.hadoop.mapreduce API
377 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.
378 ```java
379 public static class ColorCountReducer extends
380 Reducer<Text, IntWritable, AvroKey<CharSequence>, AvroValue<Integer>> {
381
382 @Override
383 public void reduce(Text key, Iterable<IntWritable> values,
384 Context context) throws IOException, InterruptedException {
385
386 int sum = 0;
387 for (IntWritable value : values) {
388 sum += value.get();
389 }
390 context.write(new AvroKey<CharSequence>(key.toString()), new AvroValue<Integer>(sum));
391 }
392 }
393 ```
394
395 ## Learning more
396 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.
397
398 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.