Hadoop二次排序原理与实现详解
通常情况下,Map输出的结果会依据Key执行默认排序操作。然而在某些场景下,不仅需要针对Key进行排序,还需对对应的Value进行排序,此时便引入了二次排序的概念。以下将详细阐述其工作机制。
1、二次排序原理
我们可以将二次排序的过程划分为几个关键阶段来理解。
Map起始阶段
在Map阶段的初期,系统会使用由job.setInputFormatClass()指定的InputFormat类,将输入的数据集切分为多个小数据块split。与此同时,InputFormat会提供一个RecordReader的实现实例。例如,若使用TextInputFormat,其提供的RecordReader会将文本的行号作为Key,该行文本内容作为Value。这构成了自定义Mapper的输入形式。随后,系统调用自定义Mapper的map方法,将一个个键值对传入进行处理。
Map最后阶段
进入Map阶段的尾声,系统首先会调用job.setPartitionerClass()设定的分区函数对Mapper的输出结果进行分区,每个分区对应一个Reducer任务。在每个分区内部,接着会调用由job.setSortComparatorClass()设置的Key比较函数类进行排序。这一过程本身即构成了一次排序。如果未通过job.setSortComparatorClass()显式设置Key比较函数类,则默认使用Key对象实现的compareTo()方法进行排序。
Reduce阶段
在Reduce阶段,reduce()方法接收所有映射到该Reduce任务的Map输出后,同样会调用job.setSortComparatorClass()方法设置的Key比较函数类对所有数据进行排序。随后开始构建对应Key的Value迭代器。此时需引入分组机制,通过job.setGroupingComparatorClass()方法设置分组函数类。只要该比较器判定两个Key相同,它们即被归为同一组,其Value放入同一个Value迭代器中,而该迭代器的Key取值为属于同一组的所有Key中的第一个Key。最后进入Reducer的reduce()方法,其输入包含所有的Key及其对应的Value迭代器,需注意输入与输出的类型必须与自定义Reducer中声明的类型保持一致。
接下来通过具体示例,直观展示二次排序的运行效果。
输入文件 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也实现了从小到大的排序,这正是二次排序的最终结果。
2、二次排序的具体流程
在本例中需要进行两次比较。首先按照第一字段排序,然后对于第一字段相同的记录,再按照第二字段排序。基于此需求,可以构造一个复合类IntPair,它包含两个字段。利用分区器对第一字段进行初步排序,再利用分区内的比较器对第二字段进行排序。二次排序的具体流程包含以下步骤。
在本例中需要进行两次比较。首先按照第一字段排序,然后对于第一字段相同的记录,再按照第二字段排序。基于此需求,可以构造一个复合类IntPair,它包含两个字段。利用分区器对第一字段进行初步排序,再利用分区内的比较器对第二字段进行排序。二次排序的具体流程包含以下步骤。
1、自定义 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)
2、自定义分区
自定义分区函数类FirstPartitioner,用于Key的第一次比较,完成对所有Key基于第一字段的排序。
public static class FirstPartitioner extends Partitioner< IntPair,IntWritable>
在Job配置中使用setPartitionerClasss()方法设置Partitioner
job.setPartitionerClasss(FirstPartitioner.Class);
3、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排序。
4、定义分组类函数
在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。
3、代码实现
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 2026-06-07 22:31:53
*/
public class IntPair implements WritableComparable{
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 {
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{
@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 {
public void reduce(IntPair key, Iterable 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);
}
}
总结
以上所述是小编给大家介绍的hadoop二次排序的原理和实现方法,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!