hadoop中的reduce函数不起作用

时间:2015-05-01 11:39:53

标签: java hadoop mapreduce word-count

我学习hadoop。我用Java编写了简单的程序。程序必须对单词进行计数(并创建包含单词和每个单词出现次数的文件),但程序只创建一个包含所有单词的文件,并在每个单词附近编号为“1”。它看起来像:

  • rmd 1
  • rmd 1
  • rmd 1
  • rmd 1
  • rmdaxsxgb 1

但我想:

  • rmd 4

  • rmdaxsxgb 1

据我所知,只有地图功能。 (我试着评论reduce函数,并得到相同的结果)。

我的代码(这是mapreduce程序的一个典型示例;它可以很容易地在互联网或有关hadoop的书籍中找到):

public class WordCount {

 public static class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
    private final static IntWritable one = new IntWritable(1);
    private Text word = new Text();

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

 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));
    }
 }


 public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();

        Job job = new Job(conf, "wordcount");
        job.setJarByClass(WordCount.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        job.setMapperClass(Map.class);
        job.setReducerClass(Reduce.class);

        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        job.waitForCompletion(true);
    } }

我在亚马逊网络服务上使用hadoop,并且不明白为什么它不能正常工作。

2 个答案:

答案 0 :(得分:0)

看起来你的hadoop集群中没有运行reducer。 您可以通过三种方式进行设置。您可以在mapred-site.xml中设置它。像

一样设置属性
<property>
 <name>mapred.reduce.tasks</name>
 <value>1</value>
</property>

或者在命令行中设置它,如

 -D mapred.reduce.tasks=1

或者在主类

中定义它
  job.setNumReduceTasks(1);

要为所有作业永久设置它,您应该在mapred-site.xml中设置该属性。

答案 1 :(得分:0)

这可能是因为API的混合和匹配。 hadoop有2个API,其中较早者为mapred,最新为mapreduce

在最新的API中,reducer将IterableIterator(旧API)进行比较,与代码中的值相同。

尝试 -

public class Reduce extends Reducer<Text, IntWritable, Text, IntWritable> {

    @Override
    protected void reduce(Text key, Iterable<IntWritable> values,
            Context context)
            throws IOException, InterruptedException {

        int sum = 0;
        for (IntWritable value:values) {
            sum += value.get();
        }
        context.write(key, new IntWritable(sum));

    }
}