侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

hadoop二次排序的原理和实现方法

技术  /  管理员 发布于 7年前   140

默认情况下,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 ,它有两个字段,先利用分区对第一字段排序,再利用分区内的比较对第二字段排序。二次排序的流程分为以下几步。

在本例中要比较两次。先按照第一字段排序,然后再对第一字段相同的按照第二字段排序。根据这一点,我们可以构造一个复合类IntPair ,它有两个字段,先利用分区对第一字段排序,再利用分区内的比较对第二字段排序。二次排序的流程分为以下几步。

1、自定义 key

所有自定义的key应该实现接口WritableComparable,因为它是可序列化的并且可比较的。WritableComparable 的内部方法如下所示

// 反序列化,从流中的二进制转换成IntPairpublic 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;  }  @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);  }}

总结

以上所述是小编给大家介绍的hadoop二次排序的原理和实现方法,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!


  • 上一条:
    详解Hadoop 运行环境搭建过程
    下一条:
    hadoop迁移数据应用实例详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 2024.07.09日OpenAI将终止对中国等国家和地区API服务(0个评论)
    • 2024/6/9最新免费公益节点SSR/V2ray/Shadowrocket/Clash节点分享|科学上网|免费梯子(0个评论)
    • 国外服务器实现api.openai.com反代nginx配置(0个评论)
    • 2024/4/28最新免费公益节点SSR/V2ray/Shadowrocket/Clash节点分享|科学上网|免费梯子(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-07
    • 2017-08
    • 2017-09
    • 2018-01
    • 2018-07
    • 2018-08
    • 2018-09
    • 2018-12
    • 2019-01
    • 2019-02
    • 2019-03
    • 2019-04
    • 2019-05
    • 2019-06
    • 2019-07
    • 2019-08
    • 2019-09
    • 2019-10
    • 2019-11
    • 2019-12
    • 2020-01
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2020-10
    • 2020-11
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-12
    • 2024-02
    • 2024-04
    • 2024-05
    • 2024-06
    • 2025-02
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客