gpt4 book ai didi

java - hadoop 中的 reduce 函数不起作用

转载 作者:可可西里 更新时间:2023-11-01 16:11:27 26 4
gpt4 key购买 nike

我在学习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);
} }

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

最佳答案

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

在最新的 API 中,与您的代码中的 Iterator(旧 API)相比,reducer 将值作为 Iterable 处理。

尝试 -

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

}
}

关于java - hadoop 中的 reduce 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29986191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com