【问题标题】:How to implement sort in hadoop?如何在hadoop中实现排序?
【发布时间】:2013-08-09 19:58:42
【问题描述】:

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

key   value
1     24
3     4
4     12
5     23

输出:

1     24
5     23
4     12
3     4

我正在处理大量数据,并且必须在一组 hadoop 机器中运行代码。 如何使用 mapreduce 做到这一点?

【问题讨论】:

  • 那么,您要按什么排序?关键还是价值?您能否提供一个示例来说明文件以及如何对其进行排序?
  • @JtheRocker 我编辑了。
  • 那么,你的钥匙是独一无二的吗?

标签: sorting hadoop mapreduce


【解决方案1】:

你可能可以这样做(我假设你在这里使用 Java)

从地图发出这样的 -

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

因此,所有需要排序的值都应该是 mapreduce 作业中的关键。 Hadoop 默认按 key 升序排序。

因此,要么你这样做是按降序排序,

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 和排序阶段将按照 24、4、12、23 的降序对您的键进行排序

评论后:

如果您需要降序 IntWritable Comparable,您可以创建一个并像这样使用它 -

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);
        }
    }
}

【讨论】:

  • 如果我有 5 台计算机运行该代码,该代码是否有效并且最终结果是绝对正确的?我需要多少减速机?
  • 是的,您可以拥有任意数量的减速器。我还假设您知道如何编写 MapReduce 作业。请试一试,告诉我它是否能解决您的问题。我认为它会与您提到的用例有关。谢谢。
  • 我使用 jobconf,它没有 setSortComparatorClass 方法。
  • 我的键是可写的。如何在我的代码中使用 DescendingKeyComparator 类?
  • 尝试使用此 DescendingIntWritableComparable 来实现降序排序而不是升序排序,但 job.setSortComparatorClass() 没有将 DescendingIntComparable.class 视为扩展 RawComparator 的类,因此它不会运行。有什么想法可以修改它以使其正常工作吗?
猜你喜欢
  • 2017-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-26
  • 2021-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多