本文以「計算學生各科平均成績」為例,分享一個完整的 MapReduce 實現。
資源文件 math
張三 99 李四 90 王五 90 趙六 60
資源文件 china
張三 79 李四 75 王五 80 趙六 90
資源文件 english
張三 89 李四 75 王五 70 趙六 90
分析:在 Map 階段,將學生姓名作為 key、成績作為 value 輸出。這樣 Reduce 階段拿到的數據就是 key:張三、value:{99,79,89}……在 Reduce 中對每位學生的成績求平均值即可。
實現:
package com.bwzy.Hadoop;
// ... 導入相關類
public class AvgSorce extends Configured implements Tool {
public static class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreElements()) {
String strName = tokenizer.nextToken();
String strSorce = tokenizer.nextToken();
context.write(new Text(strName), new IntWritable(Integer.parseInt(strSorce)));
}
}
}
public static class Reduce extends Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
int num = 0;
for (IntWritable sorce : values) {
sum += sorce.get();
num++;
}
context.write(key, new IntWritable((int)(sum / num)));
}
}
@Override
public int run(String[] arg0) throws Exception {
Job job = new Job(getConf());
job.setJobName("AvgSorce");
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
FileInputFormat.setInputPaths(job, new Path(arg0[0]));
FileOutputFormat.setOutputPath(job, new Path(arg0[1]));
return job.waitForCompletion(true) ? 0 : 1;
}
public static void main(String[] args) throws Exception {
System.exit(ToolRunner.run(new AvgSorce(), args));
}
}
運行步驟:
hadoop fs -mkdir /自定義/自定義/input;上傳文件:hadoop fs -put /home/user/Document/math /自定義/自定義/input。hadoop jar AvgSorce.jar com.bwzy.hadoop.AvgSorce /自定義/自定義/input /自定義/自定義/output。Hadoop 會自動創建 output 目錄,其中一個文件存放運行結果。若重新運行,需先刪除 output 目錄,否則系統會認為結果已存在。運行結果:
張三 89 李四 80 王五 80 趙六 80