Ответ 1
Это должно работать:
//Assuming the pair second type has an Ordering, which is the case for Int
rdd.sortBy(_._2) // same as rdd.sortBy(pair => pair._2)
(Хотя вы можете захотеть взять ключ к учетной записи, когда есть связи.)
У меня есть пара RDD искры (ключ, счет), как показано ниже
Array[(String, Int)] = Array((a,1), (b,2), (c,1), (d,3))
Использование spark scala API, как получить новую пару RDD, которая сортируется по значению?
Требуемый результат: Array((d,3), (b,2), (a,1), (c,1))
Это должно работать:
//Assuming the pair second type has an Ordering, which is the case for Int
rdd.sortBy(_._2) // same as rdd.sortBy(pair => pair._2)
(Хотя вы можете захотеть взять ключ к учетной записи, когда есть связи.)
Сортировка по ключу и значению в порядке возрастания и убывания
val textfile = sc.textFile("file:///home/hdfs/input.txt")
val words = textfile.flatMap(line => line.split(" "))
//Sort by value in descending order. For ascending order remove 'false' argument from sortBy
words.map( word => (word,1)).reduceByKey((a,b) => a+b).sortBy(_._2,false)
//for ascending order by value
words.map( word => (word,1)).reduceByKey((a,b) => a+b).sortBy(_._2)
//Sort by key in ascending order
words.map( word => (word,1)).reduceByKey((a,b) => a+b).sortByKey
//Sort by key in descending order
words.map( word => (word,1)).reduceByKey((a,b) => a+b).sortByKey(false)
Это можно сделать другим способом, применив sortByKey после замены ключа и значения
//Sort By value by swapping key and value and then using sortByKey
val sortbyvalue = words.map( word => (word,1)).reduceByKey((a,b) => a+b)
val descendingSortByvalue = sortbyvalue.map(x => (x._2,x._1)).sortByKey(false)
descendingSortByvalue.toDF.show
descendingSortByvalue.foreach {n => {
val word= n._1
val count = n._2
println(s"$word:$count")}}