reduce函数不起作用

c9qzyr3d  于 2021-06-02  发布在  Hadoop
关注(0)|答案(2)|浏览(432)

我正在学习hadoop。我用java写了一个简单的程序。程序必须对单词进行计数(并用单词和每个单词出现的次数来创建文件),但程序只创建一个包含所有单词的文件,并且在每个单词附近都用数字“1”。它看起来像:
风险管理部1
风险管理部1
风险管理部1
风险管理部1
rmdaxsxgb 1
但我想:
风险管理部4
rmdaxsxgb 1
据我所知,只适用于Map功能(我试着注解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);
    } }

我在amazonweb服务上使用hadoop,不明白为什么它不能正常工作。

sz81bmfz

sz81bmfz1#

这可能是因为API的混合和匹配。hadoop有两个api mapred 最新的是 mapreduce .
在最新的api中,reducer将值作为 Iterable 相比 Iterator (旧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));

    }
}
50pmv0ei

50pmv0ei2#

看起来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中设置该属性。

相关问题