MapReduce编程实例之自定义分区

任务描述:

一组数据,按照年份的不同将其分别存放在不同的文件里

example Data:

2013 1
2013 5
2014 5
2014 8
2015 9
2015 4

Code:

 

package mrTest;

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

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class zidingyiPartition {

	public static class myPartition extends Partitioner<LongWritable, LongWritable>{

		public int getPartition(LongWritable key, LongWritable value, int numTaskReduces) {
			// TODO Auto-generated method stub
			if(key.get()==2013){
				return 0;
			}else if(key.get()==2014){
				return 1;
			}else{
				return 2;
			}
		}
		
	}
	
	public static class Map extends Mapper<Object, Text, LongWritable,LongWritable>{
		public void map(Object key, Text value, Context context) throws IOException, InterruptedException{
				String[] line = value.toString().split("\t");
				context.write( new LongWritable(Integer.parseInt(line[0])) ,  new LongWritable(Integer.parseInt(line[1])) );
		}
	}
	
	public static class Reduce extends Reducer<LongWritable, LongWritable, LongWritable, LongWritable>{
		public void reduce(LongWritable key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException{
			for (LongWritable longWritable : values) {
				context.write(key, longWritable);
			}
		}
	}
	
	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
		// TODO Auto-generated method stub

		Job job = new Job();
		job.setJarByClass(zidingyiPartition.class);
		//  1
		FileInputFormat.addInputPath(job, new Path(args[0]));
		// 2
		job.setMapperClass(Map.class);
	    job.setMapOutputKeyClass(LongWritable.class);
	    job.setMapOutputValueClass(LongWritable.class);
	    //   3
	    job.setPartitionerClass(myPartition.class);
	    //  4
	    //  5
	    job.setNumReduceTasks(3);
	    //  6
	    job.setReducerClass(Reduce.class);
	    job.setOutputKeyClass(LongWritable.class);
	    job.setOutputValueClass(LongWritable.class);
	    //  7
	    FileOutputFormat.setOutputPath(job, new Path(args[1]));
	    //  8
	    System.exit(job.waitForCompletion(true)? 0 : 1);
	}

}

结果展示:

 


搜索与推荐Wiki

扫一扫 关注微信公众号!号主 专注于搜索和推荐系统,尝试使用算法去更好的服务于用户,包括但不局限于机器学习,深度学习,强化学习,自然语言理解,知识图谱,还不定时分享技术,资料,思考等文章!


                             【技术服务】,详情点击查看:https://mp.weixin.qq.com/s/PtX9ukKRBmazAWARprGIAg 


外包服务

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值