hadoop groupingComparator 与 secondary sort

https://blog.csdn.net/groovy2007/article/details/44408583

《hadoop权威指南》里的例子:有许多气象记录,需要找出每年的最高温度,通过secondary sort实现。(这个任务其实没有必要使用secondary sort,这里只是为了演示)

map-reduce的shuffle阶段,只会根据key进行排序,而同一个key的value是无序的,所以要把年份和温度都放在key里面。map的输出:key为year-temperature pair,value为null。job的partitioner设为根据年份进行hash(将同一年份的数据发送到同一个reducer)。job的sortComparator根据年份和温度进行比较。job的groupingComparator只根据年份进行比较。完整代码在此。

reducer的代码很简单,只有一行:将key写出即可。输出就是每个年份以及当年的最高气温。

[java]  view plain  copy
  1. void reduce(IntPair key, Iterable<NullWritable> values, Context context) {  
  2.     context.write(key, NullWritable.get());  
  3. }  

groupingComparator的作用是什么?书中对此语焉不详,只说将相同年份的数据分到一组。网上的解释也大多是错误的。

误解:reducer会根据groupingComparator对数据进行排序。略一思考就会发现这不合逻辑,如果reduce需要排序的话,那么map阶段的排序就没有必要了,反正到了reducer这里还会被打乱。

hadoop官方文档对groupingComparator的解释是:controls which keys are grouped together for a single call to Reducer.reduce()。那么到底是如何control的呢?看下面的例子。

样本数据如下,第一列是key,第二列是value。

1 12
4 41
5 52
8 82
1 11
1 13
8 83
8 81
5 51
5 53
4 43
4 42

比较一下三种操作的输出:

不指定groupingComparator:
1:12,11,13,
4:41,43,42,
5:52,51,53,
8:82,83,81,
指定Less5GroupComparator,即将小于5的key分为一组,其余一组:
1:12,11,13,41,43,42,
5:52,51,53,82,83,81,
指定Sum9GroupComparator,即相加等于9的key分为一组:
1:12,11,13,
4:41,43,42,52,51,53,
8:82,83,81,

代码如下:

[java]  view plain  copy
  1. import java.io.IOException;  
  2.   
  3. import org.apache.hadoop.fs.Path;  
  4. import org.apache.hadoop.io.IntWritable;  
  5. import org.apache.hadoop.io.LongWritable;  
  6. import org.apache.hadoop.io.Text;  
  7. import org.apache.hadoop.io.WritableComparable;  
  8. import org.apache.hadoop.io.WritableComparator;  
  9. import org.apache.hadoop.mapreduce.Job;  
  10. import org.apache.hadoop.mapreduce.Mapper;  
  11. import org.apache.hadoop.mapreduce.Reducer;  
  12. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;  
  13. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;  
  14.   
  15.   
  16. public class GroupingComparatorExample {  
  17.     public static class MyMapper  
  18.     extends Mapper {  
  19.         public void map(LongWritable key, Text value, Context context)  
  20.                 throws IOException, InterruptedException {  
  21.             String[] fields = value.toString().split(" ");  
  22.             if(fields.length==2) {  
  23.                 int k = Integer.parseInt(fields[0]);  
  24.                 int v = Integer.parseInt(fields[1]);  
  25.                 context.write(new IntWritable(k), new IntWritable(v));  
  26.             }  
  27.         }  
  28.     }  
  29.   
  30.     public static class MyReducer  
  31.     extends Reducer {  
  32.         public void reduce(IntWritable key, Iterable values, Context context)  
  33.                 throws IOException, InterruptedException {  
  34.             System.out.print(key+":");  
  35.             for(IntWritable v : values)  
  36.                 System.out.print(v+",");  
  37.             System.out.println();  
  38.         }  
  39.     }  
  40.       
  41.     public static class Sum9GroupComparator extends WritableComparator {  
  42.         protected Sum9GroupComparator() {  
  43.           super(IntWritable.classtrue);  
  44.         }  
  45.           
  46.         public int compare(WritableComparable w1, WritableComparable w2) {  
  47.             IntWritable i1 = (IntWritable) w1;  
  48.             IntWritable i2 = (IntWritable) w2;  
  49.             if(i1.get()+i2.get() == 9return 0;  
  50.             return i1.compareTo(i2);  
  51.         }  
  52.       }  
  53.       
  54.     public static class Less5GroupComparator extends WritableComparator {  
  55.         protected Less5GroupComparator() {  
  56.           super(IntWritable.classtrue);  
  57.         }  
  58.           
  59.         public int compare(WritableComparable w1, WritableComparable w2) {  
  60.             int i1 = ((IntWritable) w1).get();  
  61.             int i2 = ((IntWritable) w2).get();  
  62.             if(i1<5 && i2<5return 0;  
  63.             if(i1>=5 && i2>=5return 0;  
  64.             return Integer.compare(i1, i2);  
  65.         }  
  66.       }  
  67.   
  68.     public static void main(String[] args) throws Exception {  
  69.         if (args.length != 2) {  
  70.             System.err.println("Usage: GroupingComparatorExample <input>");  
  71.             System.exit(-1);  
  72.         }  
  73.   
  74.         Job job = new Job();  
  75.         job.setJarByClass(GroupingComparatorExample.class);  
  76.         job.setJobName("GroupingComparatorExample");  
  77.   
  78.         FileInputFormat.addInputPath(job, new Path(args[0]));  
  79.         FileOutputFormat.setOutputPath(job, new Path(args[1]));  
  80.   
  81.         job.setMapperClass(MyMapper.class);  
  82.         job.setReducerClass(MyReducer.class);  
  83.   
  84.         job.setOutputKeyClass(IntWritable.class);  
  85.         job.setOutputValueClass(IntWritable.class);  
  86.           
  87.         //job.setGroupingComparatorClass(Less5GroupComparator.class);  
  88.         //job.setGroupingComparatorClass(Sum9GroupComparator.class);  
  89.   
  90.         System.exit(job.waitForCompletion(true) ? 0 : 1);  
  91.     }  
  92. }  

从第一组输出可以看到:数据已经按key排序,同一个key里的value是无序的。另外可以推测,mapper使用的排序算法是稳定的,因为同一个key的values的顺序与输入相同。

第二组输出已经正确地将数据分成了两组,并且每一组的key是该组里面key的第一个值。(即key为1和5,而不是4和8)

第三组,key为4和5的已经正确地归为了一组,但是1和8呢。实际上goupingComparator并不进行任何排序操作,只是依次取出reducer收到的key-value对,然后比较当前key与前一个key,如果比较的结果为0,就认为是同一个group,对同一个group里的数据进行一次reduce调用。

org.apache.hadoop.mapreduce.Reducer的实现已经明白无误地说明了这一点:

[java]  view plain  copy
  1. //以下代码来自hadoop-2.4.1  
  2.   
  3. //org.apache.hadoop.mapreduce.Reducer.run()主要代码如下  
  4. public void run(Context context) throws IOException, InterruptedException {  
  5.     setup(context);  
  6.     try {  
  7.         while (context.nextKey()) {  
  8.             reduce(context.getCurrentKey(), context.getValues(), context);  
  9.         }  
  10.     } finally {  
  11.         cleanup(context);  
  12.     }  
  13. }  
  14.   
  15. //context.getValues()将会使用如下的迭代器进行遍历  
  16. //ReduceContextImpl.ValueIterator  
  17. protected class ValueIterator implements ReduceContext.ValueIterator {  
  18.     public boolean hasNext() {  
  19.         return firstValue || nextKeyIsSame;  
  20.     }  
  21.   
  22.     public VALUEIN next() {  
  23.         // if this is the first record, we don't need to advance  
  24.         if (firstValue) {  
  25.             firstValue = false;  
  26.             return value;  
  27.         }  
  28.         // if this isn't the first record and the next key is different, they  
  29.         // can't advance it here.  
  30.         if (!nextKeyIsSame) {  
  31.             throw new NoSuchElementException("iterate past last value");  
  32.         }  
  33.         // otherwise, go to the next key/value pair  
  34.         nextKeyValue();  
  35.         return value;  
  36.     }  
  37. }  
  38.   
  39. //这里的comparator就是job.setGroupingComparator()时设置的  
  40. //org.apache.hadoop.mapreduce.task.ReduceContextImpl.nextKeyValue()  
  41. public boolean nextKeyValue() throws IOException, InterruptedException {  
  42.     //...  
  43.     hasMore = input.next();  
  44.     if (hasMore) {  
  45.         nextKey = input.getKey();  
  46.         nextKeyIsSame = comparator.compare(currentRawKey.getBytes(), 0, currentRawKey.getLength(),   
  47.             nextKey.getData(), nextKey.getPosition(), nextKey.getLength() - nextKey.getPosition()  
  48.             ) == 0;  
  49.     } else {  
  50.         nextKeyIsSame = false;  
  51.     }  
  52.     inputValueCounter.increment(1);  
  53. }  
  54.        

另外,如果不设置groupingComparator的话,使用的就是map阶段排序用的comparator。

[java]  view plain  copy
  1. // org.apache.hadoop.mapreduce.Job  
  2. public RawComparator getOutputValueGroupingComparator() {  
  3.     Class<? extends RawComparator> theClass = getClass(  
  4.     JobContext.GROUP_COMPARATOR_CLASS, null, RawComparator.class);  
  5.     if (theClass == null) {  
  6.         return getOutputKeyComparator();  
  7.     }  
  8.     return ReflectionUtils.newInstance(theClass, this);  
  9. }  


package com.lyl.hello;

import java.io.IOException;

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.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;


public class GroupingComparatorExample {
    public static class MyMapper
            extends Mapper<LongWritable, Text, IntWritable, IntWritable> {
        public void map(LongWritable key, Text value, Context context)
                throws IOException, InterruptedException {
            String[] fields = value.toString().split(" ");
            System.out.println("fields is :" + fields);
            if(fields.length==2) {
                int k = Integer.parseInt(fields[0]);
                int v = Integer.parseInt(fields[1]);
                context.write(new IntWritable(k), new IntWritable(v));
            }
        }
    }

    public static class MyReducer
            extends Reducer<IntWritable, IntWritable, IntWritable, IntWritable> {
        public void reduce(IntWritable key, Iterable<IntWritable> values, Context context)
                throws IOException, InterruptedException {
            System.out.print(key+":");
            for( IntWritable v : values)
                System.out.print(key+"&"+v+",");
            System.out.println();
        }
    }

    public static class Sum9GroupComparator extends WritableComparator {
        protected Sum9GroupComparator() {
            super(IntWritable.class, true);
        }

        public int compare(WritableComparable w1, WritableComparable w2) {
            IntWritable i1 = (IntWritable) w1;
            IntWritable i2 = (IntWritable) w2;
            if(i1.get()+i2.get() == 9) return 0;
            return i1.compareTo(i2);
        }
    }

    public static class Less5GroupComparator extends WritableComparator {
        protected Less5GroupComparator() {
            super(IntWritable.class, true);
        }

        public int compare(WritableComparable w1, WritableComparable w2) {
            int i1 = ((IntWritable) w1).get();
            int i2 = ((IntWritable) w2).get();
            if(i1<5 && i2<5) return 0;
            if(i1>=5 && i2>=5) return 0;
            return Integer.compare(i1, i2);
        }
    }

    public void run() throws IOException, InterruptedException, ClassNotFoundException{
        String inputPath="file:///Users/user/Documents/LYL/GroupingComparatorExample.txt";
        String outpuPath="file:///Users/user/Documents/LYL/GroupingComparatorExample_out";

        System.out.println("inpath is :" + inputPath);

        Job job = new Job();
        job.setJarByClass(GroupingComparatorExample.class);
        job.setJobName("GroupingComparatorExample");

        FileInputFormat.addInputPath(job, new Path(inputPath));
        FileOutputFormat.setOutputPath(job, new Path(outpuPath));

        job.setMapperClass(MyMapper.class);
        job.setReducerClass(MyReducer.class);

        job.setOutputKeyClass(IntWritable.class);
        job.setOutputValueClass(IntWritable.class);

        //job.setGroupingComparatorClass(Less5GroupComparator.class);
        job.setGroupingComparatorClass(Sum9GroupComparator.class);
        System.out.println("*********** :" );
        job.waitForCompletion(true);
        //System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
    public static void main(String[] args) throws Exception {
        /*if (args.length != 2) {
            System.err.println("Usage: GroupingComparatorExample <input>");
            System.exit(-1);
        }*/
        GroupingComparatorExample gce=new GroupingComparatorExample();
        gce.run();


    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值