运行 MapReduce 任务
在这一步中,你将学习如何在存储在 HDFS 上的数据上运行 MapReduce 任务,利用并行处理的能力高效分析大规模数据集。
MapReduce 是一种编程模型,用于在机器集群上并行处理大规模数据集。它包含两个主要阶段:
-
Map(映射):输入数据被分割成较小的块,每个块由一个称为“mapper”的独立任务处理。Mapper 处理数据并生成键值对。
-
Reduce(归约):Mapper 的输出按键排序和分组,每个组由一个称为“reducer”的独立任务处理。Reducer 将每个键关联的值合并并生成最终结果。
让我们运行一个简单的 MapReduce 任务,统计文本文件中单词的出现次数。首先,创建一个名为 WordCount.java
的 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 WordCount {
public static class TokenizerMapper
extends Mapper<Object, Text, Text, IntWritable>{
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(Object key, Text value, Context context
) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
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, "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);
}
}
接下来,编译 Java 文件:
mkdir ~/wordcount
javac -source 8 -target 8 -classpath $(hadoop classpath) -d ~/wordcount WordCount.java
jar -cvf ~/wordcount.jar -C ~/wordcount .
最后,运行 MapReduce 任务:
hadoop jar ~/wordcount.jar WordCount /home/hadoop/input/file.txt /home/hadoop/output
WordCount
类定义了一个 MapReduce 任务,用于统计文本文件中单词的出现次数。TokenizerMapper
类将每行输入文本分词并生成 (word, 1) 键值对。IntSumReducer
类对每个单词的值(计数)进行求和,并生成最终的 (word, count) 对。
Java 文件被编译并打包成 JAR 文件,然后使用 hadoop jar
命令执行。输入文件路径 (/home/hadoop/input/file.txt
) 和输出目录路径 (/home/hadoop/output
) 作为参数提供。