mapreudce操作
统计文件中单词出现次数
将mapreduce程序打jar包,放到hadoop机器上
执行hadoop jar xsf.jar mapreduce.Dirverx /123 /usr/local/server/hadoop-2.10.0/out
mapreduce.Dirverx为driver类全限定类名
/123: 为输入文件路径默认从hdfs上读取
/usr/local/server/hadoop-2.10.0/out:为结果输出路径
查看输出结果
mapreduce流程
mapreduce程序包含map方法、reduce方法、driver方法
(1)Map方法对文件切片的每行数据进行处理,入参为(行首的偏移量,每行内容)组成的key,value键值对。对每行内容进行处理,分割出单词,通过上下文context输出(单词,出现次数1)键值对
public class Mapperx extends Mapper<LongWritable, Text,Text, IntWritable> {
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
// AAA BBB CCCC
String line = value.toString();
// 切分数据
String[] words = line.split(" ");
for (String word : words){
// AAA 1 BBB 1 CCCC 1
context.write(new Text(word),new IntWritable(1));
}
}
}
(2)对map阶段输出的键值对进行处理,相同的key为一组。Reduce方法入参(key,相同key的value集合)。进行求和后输出。
public class Reducex extends Reducer<Text, IntWritable,Text,IntWritable> {
@Override
protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable value : values){
sum += value.get();
}
// AAA 2
context.write(key,new IntWritable(sum));
}
}
(3)driver对mapreduce任务进行定义配置并提供执行入口
public class Dirverx {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
Job job = Job.getInstance(new Configuration());
job.setJarByClass(Dirverx.class);
job.setMapperClass(Mapperx.class);
job.setReducerClass(Reducex.class);
//map输出类型
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
// 输出结果
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
// 文件输入输出路径
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job,new Path(args[1]));
// 提交
boolean b = job.waitForCompletion(true);
System.exit(b ?0:1);
}
}
(1) 大文件被分为多个切片,每个切片由一个MapTask进程处理。默认每次读取切片的一行,调用map方法。
(2) Map方法输出的结果键值对再写入环形缓存区前,调用part方法获取该key对应的分区号。默认key的hash值 % 设置的reduceTask数量。
(3) 缓冲区快写满,对存储数据进行快速排序后,写入本地磁盘。
(4) 程序从多台机器上将多个文件切片处理后的结果,下载后进行汇总归并为一个文件
(5) 对文件中相邻两个key进行比较,最终将key相同的value集合调用reduce方法处理,最终输出到hdfs。