Hadoop之——自定义分组比较器实现分组功能

转载请注明出处:http://blog.csdn.net/l1028386804/article/details/46287985

不多说,直接上代码,大家都懂得

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);
		}

	}
}
时间: 2024-08-03 10:14:00

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.mapredu

Hadoop mapreduce自定义分组RawComparator

本文发表于本人博客. 今天接着上次[Hadoop mapreduce自定义排序WritableComparable]文章写,按照顺序那么这次应该是讲解自定义分组如何实现,关于操作顺序在这里不多说了,需要了解的可以看看我在博客园的评论,现在开始. 首先我们查看下Job这个类,发现有setGroupingComparatorClass()这个方法,具体源码如下: /** * Define the comparator that controls which keys are grouped toge

solr4.5分组查询、统计功能介绍

说到分组统计估计大家都不会陌生,就是数据库的group by语句,但是当我们采用solr4.5全文检索时,数据库提供再好的sql语句都没有任何的意义了,那么在solr4.5中我们如何做到分组统计呢?其实很简单,下面我们来看看怎么做. 示例场景: 现在有个电子商务网站的产品搜索功能,不同的商家发布不同的产品,我们想通过关键词"手机"去查找不同商家下面有多少有关手机的产品.假设索引库的结构是产品id(id).产品标题(title).产品价格(price).商家id(companyId).

Java8自定义条件让集合分组

/** * 将一个指定类型对象的集合按照自定义的一个操作分组: 每组对应一个List.最终返回结果类型是:List<List<T>> * * @param <T> */ static class GroupToList<T> implements Collector<T, List<List<T>>, List<List<T>>> { /** * 集合中对象两两比较,满足自定义的条件(operati

Hadoop mapreduce自定义排序WritableComparable

本文发表于本人博客. 今天继续写练习题,上次对分区稍微理解了一下,那根据那个步骤分区.排序.分组.规约来的话,今天应该是要写个排序有关的例子了,那好现在就开始! 说到排序我们可以查看下hadoop源码里面的WordCount例子中对LongWritable类型定义,它实现抽象接口WritableComparable,代码如下: public interface WritableComparable<T> extends Writable, Comparable<T> { } pub

sql分别用日期、月、年 分组 group by 分组,datepart函数

标签: datepart函数sql分别用日期月年 分组group by 分组 2013-12-26 15:31 20764人阅读 评论(1) 收藏 举报 分类: SQL Server(21) 版权声明:本文为博主原创文章,未经博主允许不得转载. [sql] view plain copy --以2013-12-10 12:56:55为例 --convert(nvarchar(10),CreateDate,120) => 2013-12-10 --DATEPART(month,CreateDate

hive分组排序函数 分组取top10

hive分组排序函数 分组取top10 语法:row_number() over( partition by 字段a order by 计算项b desc) rank --这里rank是别名 Partition by:类似hive的建表,分区的意思 这里按字段a分区,对计算项b进行降序排序 实例: 要取top10品牌,各品牌的top10渠道,各品牌的top10渠道中各渠道的top10档期 1) 取top10品牌 Select 品牌,count/sum/其他() as num from tb_na

commoncrawl 源码库是用于 Hadoop 的自定义 InputFormat 配送实现

commoncrawl 源码库是用于 Hadoop 的自定义 InputFormat 配送实现. Common Crawl 提供一个示例程序 BasicArcFileReaderSample.java (位于 org.commoncrawl.samples) 用来配置 InputFormat. commoncrawl / commoncrawl Watch414 Fork86 CommonCrawl Project Repository — More... http://www.commoncr

黑马程序员——java——自定义一个比较器,对TreeSet 集合中的元素按指定方法来排序

自定义一个比较器,对TreeSet 集合中的元素按指定方法来排序 import java.util.Comparator; import java.util.Iterator; import java.util.TreeSet; //自定义一个比较器 class Mycompare implements Comparator { @Override public int compare(Object o1, Object o2) { // TODO Auto-generated method s