按简单顺序考虑的两个选项是:
在 Reduce 中切换键/值
修改reduce的输出来切换key和value。例如,Hadoops example WordCount job 中的 reduce 将更改为:
public static class IntSumReducer 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(result, key);
}
}
这里的context.write(result, key); 已更改为切换键和值。
使用第二个仅地图作业
您可以使用 Hadoop 提供的InverseMapper (Source) 运行 Map only (0 reducers) 作业来切换键和值。所以你只需要第二份工作,只需要编写驱动程序,看起来像:
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "Switch inputs");
job.setJarByClass(WordCount.class);
job.setMapperClass(InverseMapper.class);
job.setNumReduceTasks(0);
job.setOutputKeyClass(IntWritable.class);
job.setOutputValueClass(Text.class);
job.setInputFormatClass(SequenceFileInputFormat.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
请注意,您可能希望第一个作业使用SequenceFileOutputFormat 写入第一个作业的输出,并使用SequenceFileInputFormat 作为第二个作业的输入。