SparkCore(4):Spark-shell的topN的3種實現
阿新 • • 發佈:2018-12-16
一、實現功能
獲取Top10 word單詞
二、實現方法
1.方法1.sortBy
val textFile = sc.textFile("file:///opt/modules/spark-2.1.0-bin-2.7.3/README.md")
val wordRDD=textFile.flatMap(_.split(" ")).map((_,1)).reduceByKey(_ + _)
wordRDD.sortBy(t => t._2 * -1).take(10)
2.方法2:sortByKey
val textFile = sc.textFile("file:///opt/modules/spark-2.1.0-bin-2.7.3/README.md") val wordRDD=textFile.flatMap(_.split(" ")).map((_,1)).reduceByKey(_ + _) wordRDD.map(t => (t._2 * -1, t)).sortByKey().map(t => t._2).take(10)
注意:t._2 * -1一定要有空格!在shell中t._2*-1是錯誤的!
3.方法3.top
將String,int的二元組進行排序,先比較第一個,再比較第二個。但是如果只想比較數字,就要把數字放到前面,所以通過swap轉換位置。
(1)wordRDD.map(_.swap).top(10).map(_.swap) 或者 (2)wordRDD.top(10)(ord = new scala.math.Ordering[(String,Int)]{ override def compare(x: (String,Int), y: (String,Int)): Int = { x._2.compare(y._2) } })