1. 引言
MapReduce(MR)是一种编程模型,用于大规模数据集(大于1TB)的并行运算。它将一个计算任务分解成多个可以并行执行的子任务,然后汇总每个子任务的结果,从而提高计算效率。本手册旨在为新手提供MR操作的基础知识和实践指导。
2. MR的基本概念
2.1 MapReduce的核心组件
- Mapper:接收输入数据,将其转换成键值对(key-value),并输出中间结果。
- Shuffle:对中间结果进行排序和分组,为Reducer提供有序的数据。
- Reducer:接收来自Mapper的中间结果,进行汇总或聚合,并输出最终结果。
2.2 MR的执行流程
- Mapper处理输入数据,生成键值对。
- Shuffle阶段对中间结果进行排序和分组。
- Reducer对有序的中间结果进行汇总或聚合。
- 输出最终结果。
3. MR编程基础
3.1 编写Mapper
public class MyMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
// 解析输入数据,生成键值对
String[] tokens = value.toString().split(",");
context.write(new Text(tokens[0]), new IntWritable(Integer.parseInt(tokens[1])));
}
}
3.2 编写Reducer
public class MyReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
// 对中间结果进行汇总
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
context.write(key, new IntWritable(sum));
}
}
3.3 编写Driver
public class MyDriver {
public static void main(String[] args) throws Exception {
// 设置作业配置参数
Job job = Job.getInstance();
job.setJarByClass(MyDriver.class);
job.setMapperClass(MyMapper.class);
job.setReducerClass(MyReducer.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);
}
}
4. MR操作实践
4.1 数据准备
在HDFS上创建输入输出目录,并上传示例数据。
hdfs dfs -mkdir -p /input
hdfs dfs -put localfile.txt /input
4.2 编译代码
使用Maven或SBT等构建工具编译代码。
mvn compile
4.3 执行作业
提交作业到Hadoop集群执行。
hadoop jar myjob.jar mydriver /input /output
4.4 查看结果
在HDFS上查看输出结果。
hdfs dfs -cat /output/*
5. 总结
本手册介绍了MR操作的基础知识和实践方法,旨在帮助新手快速上手MR编程。在实际应用中,根据具体需求,可对MR作业进行优化和调整,提高计算效率。