如何在hadoop中实现排序?

093gszye  于 2021-06-03  发布在  Hadoop
关注(0)|答案(1)|浏览(370)

我的问题是对文件中的值进行排序。键和值是整数,需要维护排序值的键。

key   value
1     24
3     4
4     12
5     23

输出:

1     24
5     23
4     12
3     4

我正在处理大量数据,必须在hadoop机器集群中运行代码。如何使用mapreduce?

zujrkrfu

zujrkrfu1#

您可能可以这样做(我假设您在这里使用java)
从Map上发出这样的声音-

context.write(24,1);
context.write(4,3);
context.write(12,4)
context.write(23,5)

因此,所有需要排序的值都应该是mapreduce工作中的关键。默认情况下,hadoop按键的升序排序。
因此,要么按降序排序,

job.setSortComparatorClass(LongWritable.DecreasingComparator.class);

或者,这个,
您需要设置一个自定义降序排序比较器,在您的工作中类似于这样。

public static class DescendingKeyComparator extends WritableComparator {
    protected DescendingKeyComparator() {
        super(Text.class, true);
    }

    @SuppressWarnings("rawtypes")
    @Override
    public int compare(WritableComparable w1, WritableComparable w2) {
        LongWritable key1 = (LongWritable) w1;
        LongWritable key2 = (LongWritable) w2;          
        return -1 * key1.compareTo(key2);
    }
}

hadoop中的suffle和sort阶段将负责按降序24、4、12、23对密钥进行排序
评论之后:
如果您需要一个降序的可写可比文件,您可以创建一个并像这样使用它-

job.setSortComparatorClass(DescendingIntComparable.class);

如果您使用的是jobconf,请使用以下命令设置

jobConfObject.setOutputKeyComparatorClass(DescendingIntComparable.class);

把下面的代码放在你的下面 main() 功能-

public static void main(String[] args) {
    int exitCode = ToolRunner.run(new YourDriver(), args);
    System.exit(exitCode);
}

//this class is defined outside of main not inside
public static class DescendingIntWritableComparable extends IntWritable {
    /**A decreasing Comparator optimized for IntWritable. */ 
    public static class DecreasingComparator extends Comparator {
        public int compare(WritableComparable a, WritableComparable b) {
            return -super.compare(a, b);
        }
        public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
            return -super.compare(b1, s1, l1, b2, s2, l2);
        }
    }
}

相关问题