How to write MapReduce programs in Java?
The basic steps for writing a MapReduce program are as follows:
- Create a class that implements the Mapper interface and overrides the map method. The map method takes a key-value pair as input, processes the input data, and outputs it as an intermediate key-value pair.
public class MyMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
word.set(tokenizer.nextToken());
context.write(word, one);
}
}
}
- Create a class that implements the Reducer interface and override the reduce method. This method takes in intermediate key-value pairs as input, aggregates the input data based on the key, and outputs the final result as key-value pairs.
public class MyReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable result = new IntWritable();
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}
- Create a configuration object to set the parameters of a MapReduce job.
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "word count");
job.setJarByClass(WordCount.class);
- Specify the path to the input data and the path to the output results.
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
- Specify the classes for Mapper and Reducer.
job.setMapperClass(MyMapper.class);
job.setCombinerClass(MyReducer.class);
job.setReducerClass(MyReducer.class);
- Define the key-value pair type of the final outcome.
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
- Submit the MapReduce job.
System.exit(job.waitForCompletion(true) ? 0 : 1);
The above are the basic steps for writing a MapReduce program. Depending on specific requirements, the logic of the Mapper and Reducer can be expanded and modified.