如何使用新的Hadoop API使用MultipleTextOutputFormat?

时间:2011-06-07 22:23:21

标签: hadoop mapreduce

我想写多个输出文件。 如何使用Job而不是JobConf执行此操作?

2 个答案:

答案 0 :(得分:1)

创建基于密钥的输出文件名的简便方法

 input data type

  //key        //value
 cupertino   apple
 sunnyvale   banana
 cupertino   pear

MultipleTextOutputFormat类

static class KeyBasedMultipleTextOutputForma extends MultipleTextOutputFormat<Text, Text> {
    @Override
    protected String generateFileNameForKeyValue(Text key, Text value, String name) {
        return key.toString() + "/" + name;
    }
} 

作业配置

 job.setOutputFormat(KeyBasedMultipleTextOutputFormat.class);

运行此代码,您将在HDFS中看到以下文件,其中/ output是作业输出目录:

 $ hadoop fs -ls /output
 /output/cupertino/part-00000
 /output/sunnyvale/part-00000
希望它有所帮助。

答案 1 :(得分:0)

文档说要改为使用org.apache.hadoop.mapreduce.lib.output.MultipleOutputs

以下是使用MultipleOutputs的代码段。不幸的是我没有写它并且没有花太多时间用它...所以我不知道为什么事情在哪里。我赞同它的希望。 :)

作业设置

job.setJobName("Job Name");
job.setJarByClass(ETLManager.class);
job.setMapOutputKeyClass(Text.class);
job.setOutputKeyClass(NullWritable.class);
job.setMapOutputValueClass(MyThing.class);
job.setMapperClass(MyThingMapper.class);
job.setReducerClass(MyThingReducer.class);
MultipleOutputs.addNamedOutput(job, Constants.MyThing_NAMED_OUTPUT, TextOutputFormat.class, NullWritable.class, Text.class);
job.setInputFormatClass(MyInputFormat.class);
FileInputFormat.addInputPath(job, new Path(conf.get("input")));
FileOutputFormat.setOutputPath(job, new Path(String.format("%s/%s", conf.get("output"), Constants.MyThing_NAMED_OUTPUT)));

减速机设置

public class MyThingReducer extends
    Reducer<Text, MyThing, NullWritable, NullWritable> {
    private MultipleOutputs     m_multipleOutputs;

     @Override
    public void setup(Context context) {
        m_multipleOutputs = new MultipleOutputs(context);
    }
    @Override
    public void cleanup(Context context) throws IOException,
            InterruptedException {
        if (m_multipleOutputs != null) {
            m_multipleOutputs.close();
        }
    }

    @Override
    public void reduce(Text key, Iterable<MyThing> values, Context context)throws IOException, InterruptedException {
        for (MyThing myThing : values) {
            m_multipleOutputs.write(Constants.MyThing_NAMED_OUTPUT, EMPTY_KEY, generateData(context, myThing), generateFileName(context, myThing));
            context.progress();
        }
    }
}

编辑:添加了对MultipleOutputs的链接。