样例文件hadoop.doc如下,试编写一个MapReduce程序,统计文件中的关键词Haddop出现的次数。样例文件Hadoop.doc的内容:The Hadoop documentation includes the information you need to get started using Hadoop. Begin with the Single Node Setuo which shows you how to set up a single-node Hadoop installation. Then move on to the Cluster Setup to learn how to set up a multi-node Hadoop installation
时间: 2024-03-20 14:41:24 浏览: 74
Hadoop中级教程(2.x)(PDF).rar
好的,这是一个典型的词频统计问题,需要编写一个MapReduce程序来解决。下面是MapReduce程序的实现过程:
1. Map阶段
对于输入文件中的每一行,我们将其切分成若干个单词。对于每个单词,我们将其作为Map的输出键,输出键值对(key, 1),表示这个单词出现了一次。同时,我们需要过滤掉非关键词“Hadoop”的单词。
2. Reduce阶段
对于每个单词,Reduce阶段将对其所有键值对(key, 1)的值进行求和,即可得到这个单词出现的总次数。对于关键词“Hadoop”,我们就能得到它在文件中出现的次数。
下面是MapReduce程序的代码实现:
```java
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class HadoopCount {
public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable>{
private final static IntWritable one = new IntWritable(1);
private Text word = new Text("Hadoop");
public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
String token = itr.nextToken();
if (token.equals("Hadoop")) {
context.write(word, one);
}
}
}
}
public static class IntSumReducer extends Reducer<Text,IntWritable,Text,IntWritable> {
private IntWritable result = new IntWritable();
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "hadoop count");
job.setJarByClass(HadoopCount.class);
job.setMapperClass(TokenizerMapper.class);
job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
```
我们可以在Hadoop集群上运行该MapReduce程序,统计Hadoop.doc文件中关键词“Hadoop”出现的次数。
阅读全文