2011-03-26 19 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)); 
}