Hadoop MapReduce,如何减少自定义对象?

时间:2017-04-01 19:56:48

标签: java hadoop

我是Hadoop的新手,我正在尝试使用Reducer类。 所以,基本上我发现了一个在线教程,他们的reduce类看起来像这样,

public class mapReducer extends Reducer<Text, IntWritable, Text, IntWritable>{
    IntWritable total = new IntWritable();
    @Override
    protected void reduce(Text key, Iterable<IntWritable> values,
            Reducer<Text, InWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException{
        for (IntWritable value: values){
             total += value.get();
        }
        context.write(key, count);
    }
} 

所以我想用myCustomObj改变总数。参考上面的例子,比如,

//..
myCustomObj total = new myCustomObj();
@Override
protected void reduce(Text key, Iterable<myCustomObj> values,
        Reducer<Text, InWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException{
    for (myCustomObj value: values){
         total.add(value);
    }
    context.write(key, total.getPrimaryAttribute());
}

目标:我想要的是hadoop完成缩减后key -> total个对象的列表。我认为上面的代码只会输出key -> primaryAttribute

建议:如果这太繁琐了,我想知道以XML格式存储我需要的详细信息。但是,我不确定map reducer背后的理论,reducer是在服务器还是客户端计算机(映射发生的地方)中执行的?如果它发生在客户端计算机上,那么我将在所有客户端计算机上拥有一点点我的XML文件。我只想将所有信息集中到1台服务器上。

我希望我明白我的问题。谢谢

编辑:我试图寻找在线资源。但是有很多定制的hadoops。我不知道我应该看什么。

1 个答案:

答案 0 :(得分:0)

为了能够减少自定义对象,首先,mapper应该将此对象作为值返回。假设对象的名称是:CustomObject,映射器定义应如下所示:

public class MyMapper extends Mapper<LongWritable, Text, Text, CustomObject> {
    @Override
    protected void map(LongWritable key, Text value,
            Mapper<LongWritable, Text, Text, CustomObject>.Context context) throws IOException, InterruptedException {
        // do you stuff here
    }
}

现在,CustomObject本身应该使用所有三种必需的方法实现WritableComparable接口(主要用于洗牌阶段要求):

  • write - 定义对象存储到磁盘的方式
  • readFields - 如何从磁盘读取存储的对象
  • compareTo - 定义对象的排序方式(您可以将其留空,因为在随机播放阶段只使用键进行排序)

Reducer签名应如下所示:

public class MyReducer extends Reducer<Text, CustomObject, Text, IntWritable>{
    @Override
    protected void reduce(Text key, Iterable<CustomObject> values,
            Reducer<Text, CustomObject, Text, IntWritable>.Context context) throws IOException, InterruptedException{
        // reducer code
    }
} 

最后,在配置作业时,应指定正确的输入/输出组合。

job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(CustomObject.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setMapperClass(MyMapper.class);
job.setReducerClass(MyReducer.class);

这应该可以解决问题。