2019独角兽企业重金招聘Python工程师标准>>>

默认情况下,Map输出的结果会对Key进行默认的排序,但是有时候需要对Key排序的同时还需要对Value进行排序,这时候就要用到二次排序了。下面我们来说说二次排序

1、二次排序原理

我们把二次排序分为以下几个阶段

Map起始阶段

在Map阶段,使用job.setInputFormatClass()定义的InputFormat,将输入的数据集分割成小数据块split,同时InputFormat提供一个RecordReader的实现。在这里我们使用的是TextInputFormat,它提供的RecordReader会将文本的行号作为Key,这一行的文本作为Value。这就是自定 Mapper的输入是<LongWritable,Text> 的原因。然后调用自定义Mapper的map方法,将一个个<LongWritable,Text>键值对输入给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()方法,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 ,它有两个字段,先利用分区对第一字段排序,再利用分区内的比较对第二字段排序。二次排序的流程分为以下几步。

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 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;}@Overridepublic void readFields(DataInput in) throws IOException{first = in.readInt();second = in.readInt();}@Overridepublic void write(DataOutput out) throws IOException{out.writeInt(first);out.writeInt(second);}@Overridepublic 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;}}@Overridepublic int hashCode(){return first * 157 + second;}@Overridepublic 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>{@Overridepublic 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);}@Overridepublic 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]));// Mapperjob.setMapperClass(Map.class);// Reducerjob.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);}
}

转载于:https://my.oschina.net/xiaoluobutou/blog/807362

MapReduce二次排序相关推荐

  1. 详细讲解MapReduce二次排序过程

    2019独角兽企业重金招聘Python工程师标准>>> 我在15年处理大数据的时候还都是使用MapReduce, 随着时间的推移, 计算工具的发展, 内存越来越便宜, 计算方式也有了 ...

  2. MapReduce二次排序分区,分组优化

    自定义分组 NameGroup package test;import org.apache.hadoop.io.RawComparator; import org.apache.hadoop.io. ...

  3. hadoop之MapReduce自定义二次排序流程实例详解

    一.概述 MapReduce框架对处理结果的输出会根据key值进行默认的排序,这个默认排序可以满足一部分需求,但是也是十分有限的.在我们实际的需求当中,往往有要对reduce输出结果进行二次排序的需求 ...

  4. 大数据【四】MapReduce(单词计数;二次排序;计数器;join;分布式缓存)

       前言: 根据前面的几篇博客学习,现在可以进行MapReduce学习了.本篇博客首先阐述了MapReduce的概念及使用原理,其次直接从五个实验中实践学习(单词计数,二次排序,计数器,join,分 ...

  5. MapReduce自定义二次排序流程

    每一条记录开始是进入到map函数进行处理,处理完了之后立马就入自定义分区函数中对其进行分区,当所有输入数据经过map函数和分区函数处理完之后,就调用自定义二次排序函数对其进行排序. MapReduce ...

  6. Hadoop Mapreduce分区、分组、二次排序过程详解

    2019独角兽企业重金招聘Python工程师标准>>> 1.MapReduce中数据流动    (1)最简单的过程:  map - reduce    (2)定制了partition ...

  7. Hadoop Mapreduce分区、分组、二次排序过程详解[转]

    徐海蛟 教学用途 1.MapReduce中数据流动 (1)最简单的过程: map - reduce (2)定制了partitioner以将map的结果送往指定reducer的过程: map - par ...

  8. Mapreduce的排序、全排序以及二次排序

    一:背景 Hadoop中虽然有自动排序和分组,由于自带的排序是按照Key进行排序的,有些时候,我们希望同时对Key和Value进行排序.自带的排序功能就无法满足我们了,还好Hadoop提供了一些组件可 ...

  9. mapreduce的二次排序 SecondarySort

    mapreduce的二次排序 SecondarySort 关于二次排序主要涉及到这么几个东西: 在0.20.0 以前使用的是 setPartitionerClass setOutputkeyCompa ...

最新文章

  1. 一种清除windows通知区域“僵尸”图标的方案——Windows7系统解决方案
  2. IDEA 配置maven
  3. Fedora 11-Alpha试用手记
  4. Pytorch torchvision完成Faster-rcnn目标检测demo及源码详解
  5. 数据结构分类概述【转载】
  6. sizeof,strlen用法详解
  7. 蚂蚁区块链正式升级为蚂蚁链:首次公布“日活”超1亿
  8. How to get the xpath by clicking an html element
  9. RabbitMQ基础进阶教程
  10. 风格迁移篇--CCPL:Contrastive Coherence Preserving Loss for Versatile Style Transfer多功能风格转换的对比连贯保持损失
  11. 数据分析统计工具有哪些?
  12. 注销 睡眠 休眠的区别
  13. React组件抽象(一): mixin
  14. epic games 无法 下载 unreal engine5
  15. 搜狗输入法转语音体验报告
  16. selenium学习——问卷星(可控比例)
  17. 【君思智慧园区】数字化园区管理系统
  18. Python学习笔记(一)数据类型
  19. kaldi教程_kaldi中特征变换
  20. Python 代码一键转流程图

热门文章

  1. html中表格与字对齐,html – 中心与表格单元格对齐
  2. cad设计院常用字体_趣谈 | 那些年我们看过的电气图纸(附CAD/EPLAN区别)
  3. mysql里面可以用正则吗_Mysql中使用正则表达式
  4. 台式计算机驱动程序未被安装,电脑未能成功安装设备驱动程序怎么办
  5. 为什么idea的断点变黑了_IntelliJ IDEA Debug回退断点
  6. c语言截图代码,截图代码 哪位大神帮我找一下错,截出来的图是这样子的
  7. php毕设,php毕设
  8. ensp删除所有命令_HCIA学习笔记——eNSP配置NAT技术
  9. 创建mysql数据库图解_mysql数据库怎么创建外键?(图文+视频)
  10. linux mysql 目录结构图_linux下mysql安装、目录结构、配置