二次排序具體實現步驟:
- 按照Ordered和serrializable接口實現自定義排序key
- 將要進行二次排序的文件假造進來生成<key,value>類型的RDD
- 使用sortbykey基於自定義的key進行二次排序
- 去除掉排序的key,只保留排序的結果
源碼如下
import org.apache.spark.{SparkConf, SparkContext}
class SecondarySortKey(val first: Int, val second: Int) extends Ordered[SecondarySortKey] with Serializable {
def compare(other: SecondarySortKey): Int = {
if(this.first - other.first != 0){
this.first - other.first
}else{
this.second - other.second
}
}
}
object SecondarySortApp {
def main(args: Array[String]) {
val conf = new SparkConf()
.setAppName(s"${this.getClass.getSimpleName}")
.setMaster("local[*]")
val sc = new SparkContext(conf)
val keyWord = sc.textFile("")
val pariWithSortKey = keyWord.map(line => (
new SecondarySortKey(line.split("")(0).toInt, line.split("")(1).toInt), line
))
val sorted = pariWithSortKey.sortByKey(false)
val sortedResult = sorted.map(sortedLine => sortedLine._2)
sortedResult.collect().foreach(println)
}
}
Ordered和Ordering的區別
Ordering繼承了java中的Comparator接口,而Ordered繼承了java的Comparable接口。
而在java中的Comparator是一個外部比較器(需要定義一個類來實現比較器),而Comparable則是一個內部比較器,在類內部重載compareTo函數