2011-03-26 18 views
0

我尝试实施的话由我自己算例如,这里是我的执行映射器:地图减少字数例如不工作

public static class Map extends Mapper<LongWritable, Text, Text, IntWritable> { 

    public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { 
     Text word = new Text();  
     String line = value.toString(); 
     StringTokenizer tokenizer = new StringTokenizer(line); 
     while (tokenizer.hasMoreTokens()) { 
      word.set(tokenizer.nextToken()); 
      context.write(word, new IntWritable(1)); 
     } 
    } 
} 

和减速机:

public static class Reduce extends Reducer<Text, IntWritable, Text, IntWritable> { 
    public void reduce(Text key, Iterator<IntWritable> values, Context context) throws IOException, InterruptedException { 
     int sum = 0; 
     while (values.hasNext()) 
      sum += values.next().get(); 
    context.write(key, new IntWritable(sum)); 
    } 
} 

但输出我得到执行此代码看起来像只映射器的输出,例如,如果输入的是“世界你好你好”,输出将为

hello 1 
hello 1 
world 1 

我也使用映射和缩减之间的组合器。任何人都可以解释我这个代码有什么问题吗?

非常感谢!

回答

3

更换您减少方法与这一个:

 @Override 
     protected void reduce(Text key, java.lang.Iterable<IntWritable> values, org.apache.hadoop.mapreduce.Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, 
       InterruptedException { 
      int sum = 0; 
      for (IntWritable value : values) { 
       sum += value.get(); 
      } 
      context.write(key, new IntWritable(sum)); 
     } 

那么底线是你不能覆盖的正确方法。 @Override有助于解决这类错误。

此外请确保您将Reduce.class设置为reduce类而不是Reducer.class!

;) HTH 约翰内斯

+0

感谢。我被困在这个问题上一两天了。 – rOrlig 2011-04-26 02:12:05

0

如果你不想用的参数传递给打减少方法,而不是替代的解决方案覆盖可以是:

@Override 
protected void reduce(Object key, Iterable values, Context context) throws 
IOException, InterruptedException { 

int sum = 0; 
Iterable<IntWritable> v = values; 
Iterator<IntWritable> itr = v.iterator(); 

while(itr.hasNext()){ 
    sum += itr.next().get(); 
} 

context.write(key, new IntWritable(sum)); 
}