首页 > 解决方案 > 如何在 Spark Scala 中按值排序

问题描述

我有一个键值对,我需要按值按降序返回前 10 个元素。正如您从下面的实际输出中看到的那样,它通过键而不是值(在本例中为 ascii 字符代码)为我提供了最高值。

例如:

//Input:
(the, 5),
(is, 10),
(me, 1)

//Expected Output:
(is, 10),
(the, 5),
(me, 1)

//Actual Output:
(the, 5),
(me, 1),
(is, 10)

我的功能:


def getActiveTaxis(taxiLines: RDD[Array[String]]): Array[(String, Int)] = {
    // Removing set up code for brevity

    val counts = keys.map(x => (x, 1))

    val sortedResult = counts.reduceByKey((a, b) => a + b).sortBy(_._2, false)

    sortedResult.top(10)
}

标签: scalaapache-spark

解决方案


您应该使用take()函数而不是top()

take()将返回前 N 个元素,而top()将在基于指定的 RDD 排序后返回前 N 个元素implicit Ordering[T]

你可以参考top() 这里的实现。


推荐阅读