MapReduce编程实践:利用MapReduce编程实现diabetes中的单词个数统计。(将代码和结果截图上传。)
时间: 2024-11-22 20:48:08 浏览: 5
大数据技术原理及应用课实验5 :MapReduce初级编程实践
MapReduce是一种分布式计算模型,主要用于处理大规模数据集。在Hadoop框架中,它简化了大数据处理流程,分为两个主要阶段:Map阶段和Reduce阶段。以下是使用Java编写的基本MapReduce程序,用于从"diabetes.csv"文件中统计每个单词的出现次数:
```java
// 导入必要的库
import java.io.IOException;
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 WordCount {
public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
@Override
protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
String[] tokens = value.toString().split("\\s+");
for (String token : tokens) {
word.set(token);
context.write(word, one);
}
}
}
public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable result = new IntWritable();
@Override
protected 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, "word count");
job.setJarByClass(WordCount.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集群上执行,并提供输入路径和输出路径。例如,假设输入文件为"data/diabetes.csv",输出到"hdfs:///output/wordcount"。然后提交作业并检查结果。
由于这是一个文本环境,无法提供实际的结果截图。运行后,你可以在指定的输出目录找到一个名为"part-r-00000"的文本文件,其中包含每个单词及其出现次数。你可以使用`hadoop fs -cat [output_path]`命令查看文件内容。
阅读全文