【发布时间】:2015-05-01 11:39:53
【问题描述】:
我正在学习 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,但不明白为什么它不能正常工作。
【问题讨论】:
标签: java hadoop mapreduce word-count