1、二次排序
对两个以上字段排序就叫二次排序
import org.apache.spark.{SparkConf, SparkContext}
import src.scala.SecondarySortKey
/**
* 使用Spark Core API实现二次排序
* 1) 自定义排序的key, 要实现Ordered和Serializable接口
* 2)将要排序的数据,映射成key为自定义排序的key,value就是原始的值
* 3)按照业务逻辑实现compare方法
* 4)使用sortByKey(false/true)算子按照自定义的key进行排序
* 5)丢弃key,取value
*/
object SecondarySort {
def main(args: Array[String]) {
val sc = new SparkContext(new SparkConf().setMaster("local").setAppName("SecondarySort"))
val rdd = sc.textFile("./datas/b.txt")
rdd.map(x => {
val splits = x.split("\t")
//返回一个tuple,sortByKey按key排序,key的排序规则在自定义类中
(new SecondarySortKey(splits(0).trim.toInt,splits(1).trim.toInt), x)
}).sortByKey().map(x => x._2).collect().foreach(println)
sc.stop()
}
}
==&