默认状况下,Map输出的结果会对Key进行默认的排序,可是有时候须要对Key排序的同时还须要对Value进行排序,这时候就要用到二次排序了。下面咱们来讲说二次排序java
一、二次排序原理算法
咱们把二次排序分为如下几个阶段apache
Map起始阶段app
在Map阶段,使用job.setInputFormatClass()定义的InputFormat,将输入的数据集分割成小数据块split,同时InputFormat提供一个RecordReader的实现。在这里咱们使用的是TextInputFormat,它提供的RecordReader会将文本的行号做为Key,这一行的文本做为Value。这就是自定 Mapper的输入是<LongWritable,Text> 的缘由。而后调用自定义Mapper的map方法,将一个个<LongWritable,Text>键值对输入给Mapper的map方法ide
Map最后阶段函数
在Map阶段的最后,会先调用job.setPartitionerClass()对这个Mapper的输出结果进行分区,每一个分区映射到一个Reducer。每一个分区内又调用job.setSortComparatorClass()设置的Key比较函数类排序。能够看到,这自己就是一个二次排序。若是没有经过job.setSortComparatorClass()设置 Key比较函数类,则使用Key实现的compareTo()方法oop
Reduce阶段this
在Reduce阶段,reduce()方法接受全部映射到这个Reduce的map输出后,也会调用job.setSortComparatorClass()方法设置的Key比较函数类,对全部数据进行排序。而后开始构造一个Key对应的Value迭代器。这时就要用到分组,使用 job.setGroupingComparatorClass()方法设置分组函数类。只要这个比较器比较的两个Key相同,它们就属于同一组,它们的 Value放在一个Value迭代器,而这个迭代器的Key使用属于同一个组的全部Key的第一个Key。最后就是进入Reducer的 reduce()方法,reduce()方法的输入是全部的Key和它的Value迭代器,一样注意输入与输出的类型必须与自定义的Reducer中声明的一致orm
接下来咱们经过示例,能够很直观的了解二次排序的原理排序
输入文件 sort.txt 内容为
40 20
40 10
40 30
40 5
30 30
30 20
30 10
30 40
50 20
50 50
50 10
50 60
输出文件的内容(从小到大排序)以下
30 10
30 20
30 30
30 40
--------
40 5
40 10
40 20
40 30
--------
50 10
50 20
50 50
50 60
从输出的结果能够看出Key实现了从小到大的排序,同时相同Key的Value也实现了从小到大的排序,这就是二次排序的结果
二、二次排序的具体流程
在本例中要比较两次。先按照第一字段排序,而后再对第一字段相同的按照第二字段排序。根据这一点,咱们能够构造一个复合类IntPair ,它有两个字段,先利用分区对第一字段排序,再利用分区内的比较对第二字段排序。二次排序的流程分为如下几步。
一、自定义 key
全部自定义的key应该实现接口WritableComparable,由于它是可序列化的而且可比较的。WritableComparable 的内部方法以下所示
// 反序列化,从流中的二进制转换成IntPair public void readFields(DataInput in) throws IOException // 序列化,将IntPair转化成使用流传送的二进制 public void write(DataOutput out) // key的比较 public int compareTo(IntPair o) // 默认的分区类 HashPartitioner,使用此方法 public int hashCode() // 默认实现 public boolean equals(Object right)
二、自定义分区
自定义分区函数类FirstPartitioner,是key的第一次比较,完成对全部key的排序。
public static class FirstPartitioner extends Partitioner< IntPair,IntWritable>
在job中使用setPartitionerClasss()方法设置Partitioner
job.setPartitionerClasss(FirstPartitioner.Class);
三、Key的比较类
这是Key的第二次比较,对全部的Key进行排序,即同时完成IntPair中的first和second排序。该类是一个比较器,能够经过两种方式实现。
1) 继承WritableComparator。
public static class KeyComparator extends WritableComparator
必须有一个构造函数,而且重载如下方法。
public int compare(WritableComparable w1, WritableComparable w2)
2) 实现接口 RawComparator。
上面两种实现方式,在Job中,能够经过setSortComparatorClass()方法来设置Key的比较类。
job.setSortComparatorClass(KeyComparator.Class);
注意:若是没有使用自定义的SortComparator类,则默认使用Key中compareTo()方法对Key排序。
四、定义分组类函数
在Reduce阶段,构造一个与 Key 相对应的 Value 迭代器的时候,只要first相同就属于同一个组,放在一个Value迭代器。定义这个比较器,能够有两种方式。
1) 继承 WritableComparator。
public static class GroupingComparator extends WritableComparator
必须有一个构造函数,而且重载如下方法。
public int compare(WritableComparable w1, WritableComparable w2)
2) 实现接口 RawComparator。
上面两种实现方式,在 Job 中,能够经过 setGroupingComparatorClass()方法来设置分组类。
job.setGroupingComparatorClass(GroupingComparator.Class);
另外注意的是,若是reduce的输入与输出不是同一种类型,则 Combiner和Reducer 不能共用 Reducer 类,由于 Combiner 的输出是 reduce 的输入。除非从新定义一个Combiner。
三、代码实现
Hadoop的example包中自带了一个MapReduce的二次排序算法,下面对 example包中的二次排序进行改进
package com.buaa; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.hadoop.io.WritableComparable; /** * @ProjectName SecondarySort * @PackageName com.buaa * @ClassName IntPair * @Description 将示例数据中的key/value封装成一个总体做为Key,同时实现 WritableComparable接口并重写其方法 * @Author 刘吉超 * @Date 2016-06-07 22:31:53 */ public class IntPair implements WritableComparable<IntPair>{ private int first; private int second; public IntPair(){ } public IntPair(int left, int right){ set(left, right); } public void set(int left, int right){ first = left; second = right; } @Override public void readFields(DataInput in) throws IOException{ first = in.readInt(); second = in.readInt(); } @Override public void write(DataOutput out) throws IOException{ out.writeInt(first); out.writeInt(second); } @Override public int compareTo(IntPair o) { if (first != o.first){ return first < o.first ? -1 : 1; }else if (second != o.second){ return second < o.second ? -1 : 1; }else{ return 0; } } @Override public int hashCode(){ return first * 157 + second; } @Override public boolean equals(Object right){ if (right == null) return false; if (this == right) return true; if (right instanceof IntPair){ IntPair r = (IntPair) right; return r.first == first && r.second == second; }else{ return false; } } public int getFirst(){ return first; } public int getSecond(){ return second; } }
package com.buaa; import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; 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.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.Partitioner; 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; /** * @ProjectName SecondarySort * @PackageName com.buaa * @ClassName SecondarySort * @Description TODO * @Author 刘吉超 * @Date 2016-06-07 22:40:37 */ @SuppressWarnings("deprecation") public class SecondarySort { public static class Map extends Mapper<LongWritable, Text, IntPair, IntWritable> { public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); StringTokenizer tokenizer = new StringTokenizer(line); int left = 0; int right = 0; if (tokenizer.hasMoreTokens()) { left = Integer.parseInt(tokenizer.nextToken()); if (tokenizer.hasMoreTokens()) right = Integer.parseInt(tokenizer.nextToken()); context.write(new IntPair(left, right), new IntWritable(right)); } } } /* * 自定义分区函数类FirstPartitioner,根据 IntPair中的first实现分区 */ public static class FirstPartitioner extends Partitioner<IntPair, IntWritable>{ @Override public int getPartition(IntPair key, IntWritable value,int numPartitions){ return Math.abs(key.getFirst() * 127) % numPartitions; } } /* * 自定义GroupingComparator类,实现分区内的数据分组 */ @SuppressWarnings("rawtypes") public static class GroupingComparator extends WritableComparator{ protected GroupingComparator(){ super(IntPair.class, true); } @Override public int compare(WritableComparable w1, WritableComparable w2){ IntPair ip1 = (IntPair) w1; IntPair ip2 = (IntPair) w2; int l = ip1.getFirst(); int r = ip2.getFirst(); return l == r ? 0 : (l < r ? -1 : 1); } } public static class Reduce extends Reducer<IntPair, IntWritable, Text, IntWritable> { public void reduce(IntPair key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { for (IntWritable val : values) { context.write(new Text(Integer.toString(key.getFirst())), val); } } } public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException { // 读取配置文件 Configuration conf = new Configuration(); // 判断路径是否存在,若是存在,则删除 Path mypath = new Path(args[1]); FileSystem hdfs = mypath.getFileSystem(conf); if (hdfs.isDirectory(mypath)) { hdfs.delete(mypath, true); } Job job = new Job(conf, "secondarysort"); // 设置主类 job.setJarByClass(SecondarySort.class); // 输入路径 FileInputFormat.setInputPaths(job, new Path(args[0])); // 输出路径 FileOutputFormat.setOutputPath(job, new Path(args[1])); // Mapper job.setMapperClass(Map.class); // Reducer job.setReducerClass(Reduce.class); // 分区函数 job.setPartitionerClass(FirstPartitioner.class); // 本示例并无自定义SortComparator,而是使用IntPair中compareTo方法进行排序 job.setSortComparatorClass(); // 分组函数 job.setGroupingComparatorClass(GroupingComparator.class); // map输出key类型 job.setMapOutputKeyClass(IntPair.class); // map输出value类型 job.setMapOutputValueClass(IntWritable.class); // reduce输出key类型 job.setOutputKeyClass(Text.class); // reduce输出value类型 job.setOutputValueClass(IntWritable.class); // 输入格式 job.setInputFormatClass(TextInputFormat.class); // 输出格式 job.setOutputFormatClass(TextOutputFormat.class); System.exit(job.waitForCompletion(true) ? 0 : 1); } }