二次排序,从字面上可以理解为在对key排序的基础上对key所对应的值value排序,也叫辅助排序。一般情况下,MapReduce框架只对key排序,而不对key所对应的值排序,因此value的排序经常是不固定的。但是我们经常会遇到同时对key和value排序的需求,例如Hadoop权威指南中的求一年的高高气温,key为年份,value为最高气温,年份按照降序排列,气温按照降序排列。还有水果电商网站经常会有按天统计水果销售排行榜的需求等等,这些都是需要对key和value同时进行排序。如下图所示:
如何设计一个MapReduce程序解决对key和value同时排序的需求呢?这就需要用到组合键、分区、分组的概念。在这里又看到分区的影子,可知分区在MapReduce是多么的重要,一定要好好掌握,是优化的重点。
按照上图中数据流转的方向,我们首先设计一个Fruit类,有三个字段,分别是日期、水果名和销量,将日期、水果名和销量作为一个复合键;接着设计一个自定义Partition类,根据Fruit的日期字段分区,让相同日期的数据流向同一个partition分区中;最后定义一个分组类,实现同一个分区内的数据分组,然后按照销量字段进行二次排序。
具体实现思路:
1、定义Fruit类,实现WritableComparable接口,并且重写compareTo、equal和hashcode方法以及序列化和反序列化方法readFields和write方法。Java类要在网络上传输必须序列化和反序列化。在Map端的map函数中将Fruit对象当做key。compareTo方法用于比较两个key的大小,在本文中就是比较两个Fruit对象的排列顺序。
2、自定义第一次排序类,继承WritableComparable或者WritableComparator接口,重写compareTo或者compare方法,。就是在Map端对Fruit对象的第一个字段进行排序
3、自定义Partition类,实现Partitioner接口,并且重写getPartition方法,将日期相同的Fruit对象分发到同一个partition中。
4、定义分组类,继承WritableComparator接口,并且重写compare方法。用于比较同一分组内两个Fruit对象的排列顺序,根据销量字段比较。日期相同的Fruit对象会划分到同一个分组。通过setGroupingComparatorClass方法设置分组类。如果不设置分组类,则按照key默认的compare方法来对key进行排序。
代码如下:
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
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;
import org.apache.hadoop.util.GenericOptionsParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* FileName: MRSecondarySort
* Author: hadoop
* Email: 3165845957@qq.com
* Date: 18-10-8 下午12:36
* Description:
*/
public class MRSecondarySort {
//使用Mapper将数据文件中的数据本身作为Mapper输出的key直接输出
public static class MRSecondarySortMapper extends Mapper<LongWritable, Text, Fruit, NullWritable> {
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
String[] data = line.split("\t");
Fruit fruit = null;
if (data.length == 3){
fruit = new Fruit(data[0],data[1],new Integer(data[2]));
}
context.write(fruit,NullWritable.get());
}
}
//使用Reducer将输入的key本身作为key直接输出
public static class MRSecondarySortReducer extends Reducer<Fruit, NullWritable, Text,NullWritable> {
@Override
protected void reduce(Fruit key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException {
String string = key.getDate()+" "+key.getName()+ " " + key.getSales();
context.write(new Text(string),NullWritable.get());
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();//设置MapReduce的配置
Path outputPath = new Path(args[1]);
FileSystem hdfs = outputPath.getFileSystem(conf);
// 判断路径是否存在,如果存在,则删除
if (hdfs.isDirectory(outputPath)){
hdfs.delete(outputPath,true);
}
String[] otherArgs = new GenericOptionsParser(conf,args).getRemainingArgs();
if(otherArgs.length < 2){
System.out.println("Usage: MRSecondarySort <in> [<in>...] <out>");
System.exit(2);
}
Job job = Job.getInstance(conf,"MRSecondarySort");
//设置主类
job.setJarByClass(MRSecondarySort.class);
//设置处理Mapper
job.setMapperClass(MRSecondarySortMapper.class);
//设置map输出的key类型
job.setMapOutputKeyClass(Fruit.class);
//设置map输出的value类型
job.setMapOutputValueClass(NullWritable.class);
//设置Reducer
job.setReducerClass(MRSecondarySortReducer.class);
//设置Reducer输出的Key类型
job.setOutputKeyClass(Text.class);
//设置Reducer输出的value类型
job.setOutputValueClass(NullWritable.class);
//设置分区数
job.setPartitionerClass(FriutPartition.class);
//设置分组函数
job.setGroupingComparatorClass(GroupComparator.class);
//设定输入路径
for (int i = 0; i < otherArgs.length-1;++i){
FileInputFormat.addInputPath(job,new Path(otherArgs[i]));
}
//设置输出路径
FileOutputFormat.setOutputPath(job, new Path(otherArgs[otherArgs.length-1]));
System.exit(job.waitForCompletion(true)?0:1);
}
}
class Fruit implements WritableComparable<Fruit> {
private static final Logger logger = LoggerFactory.getLogger(Fruit.class);
private String date;
private String name;
private Integer sales;
public Fruit() {
}
public Fruit(String date, String name, Integer sales) {
this.date = date;
this.name = name;
this.sales = sales;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSales() {
return sales;
}
public void setSales(Integer sales) {
this.sales = sales;
}
@Override
public boolean equals(Object o) {
if (o == null)
return false;
if (this == o)
return true;
if (o instanceof Fruit){
Fruit fruit = (Fruit) o;
return fruit.getDate().equals(this.getDate()) && fruit.getName().equals(this.getName())&&(this.getSales()==fruit.getSales());
}else {
return false;
}
}
@Override
public int hashCode() {
return this.date.hashCode() * 157 + this.sales + this.name.hashCode();
}
@Override
public String toString() {
return this.date+" "+ this.name+" "+ this.sales;
}
@Override
public int compareTo(Fruit fruit) {
int result = this.date.compareTo(fruit.getDate());
if (result == 0){
int result1 = this.sales - fruit.getSales();
if (result1 == 0){
double result2 = this.name.compareTo(fruit.getName());
if (result2 > 0){
return -1;
}else if (result2 < 0){
return 1;
}else {
return 0;
}
}else if(result1 > 0){
return -1;
}else if (result1 < 0){
return 1;
}
}else if (result >0){
return -1;
}else {
return 1;
}
return 0;
}
@Override
public void write(DataOutput dataOutput) throws IOException {
dataOutput.writeUTF(this.date);
dataOutput.writeUTF(this.name);
dataOutput.writeInt(this.sales);
}
@Override
public void readFields(DataInput dataInput) throws IOException {
this.date = dataInput.readUTF();
this.name = dataInput.readUTF();
this.sales = dataInput.readInt();
}
}
class FriutPartition extends Partitioner<Fruit, NullWritable> {
@Override
public int getPartition(Fruit fruit, NullWritable nullWritable, int i) {
return Math.abs(Integer.parseInt(fruit.getDate()) * 127 ) % i;
}
}
class GroupComparator extends WritableComparator {
protected GroupComparator(){
super(Fruit.class,true);
}
@Override
public int compare(WritableComparable a, WritableComparable b) {
Fruit x = (Fruit)a;
Fruit y = (Fruit)b;
if (!x.getDate().equals(y.getDate())){
return x.getDate().compareTo(y.getDate());
}else{
return x.getSales().compareTo(y.getSales());
}
}
}
测试数据:
20180906 Apple 200
20180904 Apple 200
20180905 Banana 100
20180906 Orange 300
20180906 Banana 400
20180904 Orange 100
20180905 Apple 400
20180904 Banana 300
20180905 Orange 500
用命令行提交:
运行结果:
20180906 Banana 400
20180906 Orange 300
20180906 Apple 200
20180905 Orange 500
20180905 Apple 400
20180905 Banana 100
20180904 Banana 300
20180904 Apple 200
20180904 Orange 100
总结:
1、在使用实现WritableComparable接口的方式实现自定义比较器时,必须有一个无参的构造函数。否则会报Unable to initialize any output collector的错误。
2、readFields和write方法中处理字段的顺序必须一致,否则会报MapReduce Error: java.io.EOFException at java.io.DataInputStream.readFully(DataInputStream.java:197)的错误。
在写代码的时候一定要仔细,特别是对于初学者来说至关重要,不然代码写出来有错误不知道错在哪里,什么错,那就很痛苦了,这是学的教训啊!!!!