具体程序就不写了,主要面对的问题有这么几个:
1.由于结果要输出打印,所以最后输出value的类型为Text,而非doubleWritable,但是wordcount为什么可以在输出时的类型设置为IntWritable?
这个应该是setoutputkeyclass和valueclass默认是map和reduce输出是一致的原因但是我改了还是不行,不知道为什么,难受啊。我还是把程序放上来吧。
这个程序是错的
public class average {
public class AddMapper extends Mapper<LongWritable, Text, Text, Text> {
Text word = new Text();
public void map(LongWritable key, Text val, Mapper.Context context) throws IOException, InterruptedException {
StringTokenizer st = new StringTokenizer(val.toString());
while (st.hasMoreElements()) {
word.set(st.nextToken());
context.write(word, new Text(st.nextToken()));
}
}
}
public class AddReducer extends Reducer<Text, Text, Text, DoubleWritable> {
DoubleWritable result = new DoubleWritable();
public void reduce(Text key, Iterable<Text> vals, Mapper.Context context) throws IOException, InterruptedException {
int s = 0;
int length = 0;
for (Text val : vals) {
s += Integer.valueOf(val.toString());
length++;
}
result.set((double) s*1.0 / length);
context.write(key, result);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "average");
job.setJarByClass(average.class);
job.setMapperClass(AddMapper.class);
job.setReducerClass(AddReducer.class);
job.setMapOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(DoubleWritable.class);
FileInputFormat.addInputPath(job,new Path(args[0]));
FileOutputFormat.setOutputPath(job,new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
2.我写了个mapper输出键值对的value类型为intwritable,即用来保存求和的加数,在reduce函数中通过for循环来计算项数,这样再通过除法求平均值就是不能跑出结果,难道所有引入的数值必须是从mapper中得到的?不该吧,太玄幻了。