hadoop wordcount 的hello world
时间: 2024-10-15 20:06:51 浏览: 30
Hadoop WordCount是一个经典的MapReduce示例程序,用于计算给定文本文件中每个单词出现的次数。以下是Hadoop MapReduce中实现WordCount的一个简单"Hello World"级别的例子:
首先,你需要有一个Mapper类,它负责读取输入数据并分解成键值对(key-value pairs)。在这个例子中,我们将每个单词作为键,值设为1。
```java
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class WordCountMapper 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();
for (String token : line.split("\\s+")) {
word.set(token);
context.write(word, one);
}
}
}
```
然后,你需要一个Reducer类,它接收Mapper阶段产生的键值对,并计算每个单词的实际计数。
```java
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class WordCountReducer 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);
}
}
```
最后,在Driver类中设置Mapper和Reducer,以及配置Job运行。
```java
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.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class WordCount {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "word count");
job.setJarByClass(WordCount.class);
job.setMapperClass(WordCountMapper.class);
job.setCombinerClass(WordCountReducer.class);
job.setReducerClass(WordCountReducer.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);
}
}
```
运行这个程序时,需要提供两个参数:一个是包含文本数据的输入文件路径,另一个是期望生成结果的输出目录。例如,你可以像这样运行:
```bash
hadoop jar your-word-count-job.jar WordCount input.txt output-dir
```
阅读全文