(三)MapReduce编程实例

时间:2021-01-03 18:22:17

MapReduce编程实例:

MapReduce编程实例(一),详细介绍在集成环境中运行第一个MapReduce程序 WordCount及代码分析

MapReduce编程实例(二),计算学生平均成绩

MapReduce编程实例(三),数据去重

MapReduce编程实例(四),排序

MapReduce编程实例(五),MapReduce实现单表关联

MapReduce编程实例(六),MapReduce实现多表关联


排序,比较简单,上代码,代码中有注释,欢迎交流。

总体是利用MapReduce本身对Key进行排序的特性和按key值有序的分配到不同的partition。Mapreduce默认会对每个reduce按text类型key按字母顺序排序,对intwritable类型按大小进行排序。

输入:

2013-11-01 aa
2013-11-02 bb
2013-11-03 cc
2013-11-04 aa
2013-11-05 dd
2013-11-06 dd
2013-11-07 aa
2013-11-09 cc
2013-11-10 ee


2013-11-01 bb 
2013-11-02 33 
2013-11-03 cc
2013-11-04 bb
2013-11-05 23 
2013-11-06 dd
2013-11-07 99 
2013-11-09 99
2013-11-10 ee

数据重复,map中每一行做为一个key,value值任意,经过shuffle之后输入到reduce中利用key的唯一性直接输出key

代码太简单,不解释,上代码:


package com.t.hadoop;

import java.io.IOException;
import java.util.HashSet;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
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;
import org.apache.hadoop.util.GenericOptionsParser;

/**
* 数据去重
* @author daT dev.tao@gmail.com
*
*/
public class Dedup {

public static class MyMapper extends Mapper<Object, Text, Text, Text>{

@Override
protected void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
context.write(value, new Text(""));
}
}

public static class MyReducer extends Reducer<Text, Text, Text, Text>{

@Override
protected void reduce(Text key, Iterable<Text> value,
Context context)
throws IOException, InterruptedException {
context.write(key, new Text(""));
}
}


public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException{
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();

if(otherArgs.length<2){
System.out.println("parameter errors!");
System.exit(2);
}

Job job = new org.apache.hadoop.mapreduce.Job(conf, "Dedup");
job.setJarByClass(Dedup.class);
job.setMapperClass(MyMapper.class);
job.setCombinerClass(MyReducer.class);
job.setReducerClass(MyReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);

FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));

System.exit(job.waitForCompletion(true)?0:1);

}

}

输出结果
2013-11-01 aa
2013-11-01 bb 
2013-11-02 33 
2013-11-02 bb
2013-11-03 cc
2013-11-03 cc 
2013-11-04 98
2013-11-04 aa
2013-11-04 bb
2013-11-05 23 
2013-11-05 93
2013-11-05 dd
2013-11-06 99
2013-11-06 dd
2013-11-07 92
2013-11-07 99 
2013-11-07 aa
2013-11-09 99
2013-11-09 aa 
2013-11-09 cc
2013-11-10 ee