1. 程式人生 > >Hadoop之——自定義分組比較器實現分組功能

Hadoop之——自定義分組比較器實現分組功能

不多說,直接上程式碼,大家都懂得

1、Mapper類的實現

	
	/**
	 * Mapper類的實現
	 * @author liuyazhuang
	 *
	 */
	static class MyMapper extends Mapper<LongWritable, Text, NewK2, LongWritable>{
		protected void map(LongWritable key, Text value, org.apache.hadoop.mapreduce.Mapper<LongWritable,Text,NewK2,LongWritable>.Context context) throws java.io.IOException ,InterruptedException {
			final String[] splited = value.toString().split("\t");
			final NewK2 k2 = new NewK2(Long.parseLong(splited[0]), Long.parseLong(splited[1]));
			final LongWritable v2 = new LongWritable(Long.parseLong(splited[1]));
			context.write(k2, v2);
		};
	}

2、Reducer類的實現

	/**
	 * Reducer類的實現
	 * @author liuyazhuang
	 *
	 */
	static class MyReducer extends Reducer<NewK2, LongWritable, LongWritable, LongWritable>{
		protected void reduce(NewK2 k2, java.lang.Iterable<LongWritable> v2s, org.apache.hadoop.mapreduce.Reducer<NewK2,LongWritable,LongWritable,LongWritable>.Context context) throws java.io.IOException ,InterruptedException {
			long min = Long.MAX_VALUE;
			for (LongWritable v2 : v2s) {
				if(v2.get()<min){
					min = v2.get();
				}
			}
			
			context.write(new LongWritable(k2.first), new LongWritable(min));
		};
	}

3、WritableComparable類的實現

	/**
	 * 問:為什麼實現該類?
	 * 答:因為原來的v2不能參與排序,把原來的k2和v2封裝到一個類中,作為新的k2
	 * @author liuyazhuang
	 */
	static class  NewK2 implements WritableComparable<NewK2>{
		Long first;
		Long second;
		
		public NewK2(){}
		
		public NewK2(long first, long second){
			this.first = first;
			this.second = second;
		}
		
		
		@Override
		public void readFields(DataInput in) throws IOException {
			this.first = in.readLong();
			this.second = in.readLong();
		}

		@Override
		public void write(DataOutput out) throws IOException {
			out.writeLong(first);
			out.writeLong(second);
		}

		/**
		 * 當k2進行排序時,會呼叫該方法.
		 * 當第一列不同時,升序;當第一列相同時,第二列升序
		 * @author liuyazhuang
		 */
		@Override
		public int compareTo(NewK2 o) {
			final long minus = this.first - o.first;
			if(minus !=0){
				return (int)minus;
			}
			return (int)(this.second - o.second);
		}
		
		@Override
		public int hashCode() {
			return this.first.hashCode()+this.second.hashCode();
		}
		
		@Override
		public boolean equals(Object obj) {
			if(!(obj instanceof NewK2)){
				return false;
			}
			NewK2 oK2 = (NewK2)obj;
			return (this.first==oK2.first)&&(this.second==oK2.second);
		}
	}

4、分組比較器RawComparator的實現

	/**
	 * 自定義分組比較器
	 * 問:為什麼自定義該類?
	 * 答:業務要求分組是按照第一列分組,但是NewK2的比較規則決定了不能按照第一列分。只能自定義分組比較器。
	 * @author liuyazhuang
	 *
	 */
	static class MyGroupingComparator implements RawComparator<NewK2>{

		@Override
		public int compare(NewK2 o1, NewK2 o2) {
			return (int)(o1.first - o2.first);
		}
		/**
		 * @param arg0 表示第一個參與比較的位元組陣列
		 * @param arg1 表示第一個參與比較的位元組陣列的起始位置
		 * @param arg2 表示第一個參與比較的位元組陣列的偏移量
		 * 
		 * @param arg3 表示第二個參與比較的位元組陣列
		 * @param arg4 表示第二個參與比較的位元組陣列的起始位置
		 * @param arg5 表示第二個參與比較的位元組陣列的偏移量
		 */
		@Override
		public int compare(byte[] arg0, int arg1, int arg2, byte[] arg3,
				int arg4, int arg5) {
			return WritableComparator.compareBytes(arg0, arg1, 8, arg3, arg4, 8);
		}
		
	}

5、程式入口Main

	public static void main(String[] args) throws Exception{
		final Configuration configuration = new Configuration();
		
		final FileSystem fileSystem = FileSystem.get(new URI(INPUT_PATH), configuration);
		if(fileSystem.exists(new Path(OUT_PATH))){
			fileSystem.delete(new Path(OUT_PATH), true);
		}
		
		final Job job = new Job(configuration, GroupApp.class.getSimpleName());
		
		//1.1 指定輸入檔案路徑
		FileInputFormat.setInputPaths(job, INPUT_PATH);
		//指定哪個類用來格式化輸入檔案
		job.setInputFormatClass(TextInputFormat.class);
		
		//1.2指定自定義的Mapper類
		job.setMapperClass(MyMapper.class);
		//指定輸出<k2,v2>的型別
		job.setMapOutputKeyClass(NewK2.class);
		job.setMapOutputValueClass(LongWritable.class);
		
		//1.3 指定分割槽類
		job.setPartitionerClass(HashPartitioner.class);
		job.setNumReduceTasks(1);
		
		//1.4 TODO 排序、分割槽
		job.setGroupingComparatorClass(MyGroupingComparator.class);
		//1.5  TODO (可選)合併
		
		//2.2 指定自定義的reduce類
		job.setReducerClass(MyReducer.class);
		//指定輸出<k3,v3>的型別
		job.setOutputKeyClass(LongWritable.class);
		job.setOutputValueClass(LongWritable.class);
		
		//2.3 指定輸出到哪裡
		FileOutputFormat.setOutputPath(job, new Path(OUT_PATH));
		//設定輸出檔案的格式化類
		job.setOutputFormatClass(TextOutputFormat.class);
		
		//把程式碼提交給JobTracker執行
		job.waitForCompletion(true);
	}

6、完整程式碼

package com.lyz.hadoop.group;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.net.URI;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.RawComparator;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
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.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.mapreduce.lib.partition.HashPartitioner;

/**
 * Hadoop實現分組操作
 * 當第一列不同時,升序;當第一列相同時,第二列升序
 * @author liuyazhuang
 *
 */
public class GroupApp {
	//要統計的檔案位置
	static final String INPUT_PATH = "hdfs://liuyazhuang:9000/input";
	//統計結果輸出的位置
	static final String OUT_PATH = "hdfs://liuyazhuang:9000/out";
	public static void main(String[] args) throws Exception{
		final Configuration configuration = new Configuration();
		
		final FileSystem fileSystem = FileSystem.get(new URI(INPUT_PATH), configuration);
		if(fileSystem.exists(new Path(OUT_PATH))){
			fileSystem.delete(new Path(OUT_PATH), true);
		}
		
		final Job job = new Job(configuration, GroupApp.class.getSimpleName());
		
		//1.1 指定輸入檔案路徑
		FileInputFormat.setInputPaths(job, INPUT_PATH);
		//指定哪個類用來格式化輸入檔案
		job.setInputFormatClass(TextInputFormat.class);
		
		//1.2指定自定義的Mapper類
		job.setMapperClass(MyMapper.class);
		//指定輸出<k2,v2>的型別
		job.setMapOutputKeyClass(NewK2.class);
		job.setMapOutputValueClass(LongWritable.class);
		
		//1.3 指定分割槽類
		job.setPartitionerClass(HashPartitioner.class);
		job.setNumReduceTasks(1);
		
		//1.4 TODO 排序、分割槽
		job.setGroupingComparatorClass(MyGroupingComparator.class);
		//1.5  TODO (可選)合併
		
		//2.2 指定自定義的reduce類
		job.setReducerClass(MyReducer.class);
		//指定輸出<k3,v3>的型別
		job.setOutputKeyClass(LongWritable.class);
		job.setOutputValueClass(LongWritable.class);
		
		//2.3 指定輸出到哪裡
		FileOutputFormat.setOutputPath(job, new Path(OUT_PATH));
		//設定輸出檔案的格式化類
		job.setOutputFormatClass(TextOutputFormat.class);
		
		//把程式碼提交給JobTracker執行
		job.waitForCompletion(true);
	}

	
	/**
	 * Mapper類的實現
	 * @author liuyazhuang
	 *
	 */
	static class MyMapper extends Mapper<LongWritable, Text, NewK2, LongWritable>{
		protected void map(LongWritable key, Text value, org.apache.hadoop.mapreduce.Mapper<LongWritable,Text,NewK2,LongWritable>.Context context) throws java.io.IOException ,InterruptedException {
			final String[] splited = value.toString().split("\t");
			final NewK2 k2 = new NewK2(Long.parseLong(splited[0]), Long.parseLong(splited[1]));
			final LongWritable v2 = new LongWritable(Long.parseLong(splited[1]));
			context.write(k2, v2);
		};
	}
	
	/**
	 * Reducer類的實現
	 * @author liuyazhuang
	 *
	 */
	static class MyReducer extends Reducer<NewK2, LongWritable, LongWritable, LongWritable>{
		protected void reduce(NewK2 k2, java.lang.Iterable<LongWritable> v2s, org.apache.hadoop.mapreduce.Reducer<NewK2,LongWritable,LongWritable,LongWritable>.Context context) throws java.io.IOException ,InterruptedException {
			long min = Long.MAX_VALUE;
			for (LongWritable v2 : v2s) {
				if(v2.get()<min){
					min = v2.get();
				}
			}
			
			context.write(new LongWritable(k2.first), new LongWritable(min));
		};
	}
	
	/**
	 * 問:為什麼實現該類?
	 * 答:因為原來的v2不能參與排序,把原來的k2和v2封裝到一個類中,作為新的k2
	 * @author liuyazhuang
	 */
	static class  NewK2 implements WritableComparable<NewK2>{
		Long first;
		Long second;
		
		public NewK2(){}
		
		public NewK2(long first, long second){
			this.first = first;
			this.second = second;
		}
		
		
		@Override
		public void readFields(DataInput in) throws IOException {
			this.first = in.readLong();
			this.second = in.readLong();
		}

		@Override
		public void write(DataOutput out) throws IOException {
			out.writeLong(first);
			out.writeLong(second);
		}

		/**
		 * 當k2進行排序時,會呼叫該方法.
		 * 當第一列不同時,升序;當第一列相同時,第二列升序
		 * @author liuyazhuang
		 */
		@Override
		public int compareTo(NewK2 o) {
			final long minus = this.first - o.first;
			if(minus !=0){
				return (int)minus;
			}
			return (int)(this.second - o.second);
		}
		
		@Override
		public int hashCode() {
			return this.first.hashCode()+this.second.hashCode();
		}
		
		@Override
		public boolean equals(Object obj) {
			if(!(obj instanceof NewK2)){
				return false;
			}
			NewK2 oK2 = (NewK2)obj;
			return (this.first==oK2.first)&&(this.second==oK2.second);
		}
	}
	
	
	/**
	 * 自定義分組比較器
	 * 問:為什麼自定義該類?
	 * 答:業務要求分組是按照第一列分組,但是NewK2的比較規則決定了不能按照第一列分。只能自定義分組比較器。
	 * @author liuyazhuang
	 *
	 */
	static class MyGroupingComparator implements RawComparator<NewK2>{

		@Override
		public int compare(NewK2 o1, NewK2 o2) {
			return (int)(o1.first - o2.first);
		}
		/**
		 * @param arg0 表示第一個參與比較的位元組陣列
		 * @param arg1 表示第一個參與比較的位元組陣列的起始位置
		 * @param arg2 表示第一個參與比較的位元組陣列的偏移量
		 * 
		 * @param arg3 表示第二個參與比較的位元組陣列
		 * @param arg4 表示第二個參與比較的位元組陣列的起始位置
		 * @param arg5 表示第二個參與比較的位元組陣列的偏移量
		 */
		@Override
		public int compare(byte[] arg0, int arg1, int arg2, byte[] arg3,
				int arg4, int arg5) {
			return WritableComparator.compareBytes(arg0, arg1, 8, arg3, arg4, 8);
		}
		
	}
}