前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Hadoop MapReduce 二次排序

Hadoop MapReduce 二次排序

作者头像
小爷毛毛_卓寿杰
发布2019-02-13 11:50:35
4270
发布2019-02-13 11:50:35
举报
文章被收录于专栏:Soul Joy Hub
代码语言:javascript
复制
package SecondarySort;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Set;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.RawComparator;
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;

public class SecondarySort {

    public static class IntPair implements WritableComparable<IntPair> {
        int first, second;

        public void set(int left, int right) {
            first = left;
            second = right;
        }

        public int getFirst() {
            return first;
        }

        public int getSecond() {
            return second;
        }

        @Override
        public void readFields(DataInput arg0) throws IOException {
            // TODO Auto-generated method stub
            first = arg0.readInt();
            second = arg0.readInt();
        }

        @Override
        public void write(DataOutput arg0) throws IOException {
            // TODO Auto-generated method stub
            arg0.writeInt(first);
            arg0.writeInt(second);
        }

        // 关键:自定义类型的比较方法
        @Override
        public int compareTo(IntPair arg0) {
            // TODO Auto-generated method stub
            if (first != arg0.first) {
                return first < arg0.first ? -1 : 1;
            } else if (second != arg0.second) {
                return second < arg0.second ? -1 : 1;
            } else {
                return 0;
            }
        }

        public int hashCode() {
            return first * 157 + second;
        }

        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 static class FirstPartitioner extends
            Partitioner<IntPair, IntWritable> { // 类型要和Mapper输出的一样

        @Override
        public int getPartition(IntPair arg0, IntWritable arg1, int arg2) {
            // TODO Auto-generated method stub
            return Math.abs((arg0.getFirst() * 127) % arg2);
        }

    }

    /*
     * 第一种方法,实现接口RawComparator 数据类型的比较在MapReduce中式及其重要的,
     * Mapreduce中有一个排序阶段,key和其他的key相比较。 针对此,Hadoop 提供的一个优化是 RawComparator
     * 
     * public static class GroupingComparator implements RawComparator<IntPair>{
     * 
     * @Override public int compare(IntPair arg0, IntPair arg1) { // TODO
     * Auto-generated method stub int l = arg0.getFirst(); int r =
     * arg0.getFirst(); return l == r ? 0 : (l < r ? -1 : 1); }
     * 
     * @Override public int compare(byte[] b1, int s1, int l1, byte[] b2, int
     * s2, int l2) { return WritableComparator.compareBytes(b1, s1,
     * Integer.SIZE/8, b2, s2, Integer.SIZE/8); } }
     */

    // 方法二
    public static class GroupingComparator extends WritableComparator {
        protected GroupingComparator() {
            super(IntPair.class, true);// 调用父类的构造函数
        }

        public int compare(WritableComparable w1, WritableComparable w2) {
            IntPair i1 = (IntPair) w1;
            IntPair i2 = (IntPair) w2;
            int l = i1.getFirst();
            int r = i2.getFirst();
            return l == r ? 0 : (l < r ? -1 : 1);
        }
    }

    public static class Map extends
            Mapper<LongWritable, Text, IntPair, IntWritable> {
        private final IntPair ip = new IntPair();
        private final IntWritable iw = new IntWritable();

        public void map(LongWritable key, Text value, Context context)
                throws IOException, InterruptedException {
            String line = value.toString();
            StringTokenizer st = new StringTokenizer(line);
            int left = 0;
            int right = 0;
            if (st.hasMoreTokens()) {
                left = Integer.parseInt(st.nextToken());
                if (st.hasMoreTokens()) {
                    right = Integer.parseInt(st.nextToken());
                }
                ip.set(left, right);
                iw.set(right);
                context.write(ip, iw);
            }
        }
    }

    public static class Reduce extends
            Reducer<IntPair, IntWritable, Text, IntWritable> {
        private final Text left = new Text();
        private static final Text SEPARATOR = new Text(
                "======================================");

        public void reduce(IntPair key, Iterable<IntWritable> values,
                Context context) throws IOException, InterruptedException {
            context.write(SEPARATOR, null);
            left.set(Integer.toString(key.getFirst()));
            for (IntWritable val : values) {
                context.write(left, val);
            }
        }
    }

    public static void main(String[] args) throws IllegalArgumentException,
            IOException, ClassNotFoundException, InterruptedException {
        // TODO Auto-generated method stub
        Configuration conf = new Configuration();
        @SuppressWarnings("deprecation")
        Job job = new Job(conf, "mysecondarysort");
        job.setJarByClass(SecondarySort.class);
        job.setMapperClass(Map.class);
        job.setReducerClass(Reduce.class);
        job.setPartitionerClass(FirstPartitioner.class);

        job.setGroupingComparatorClass(GroupingComparator.class);

        job.setMapOutputKeyClass(IntPair.class);
        job.setMapOutputValueClass(IntWritable.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);
        FileInputFormat.setInputPaths(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }

}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016年08月05日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档