承接上一個文檔《 》
進一步延伸,做一個詞頻前十的統計練習
邏輯:在reduceByKey的基礎上,首先要根據key對應的value值進行排序(降序排序),取前10個的結果就是Top10
<code>val reduceByKeyRDD = sc.textFile("file:///opt/bigdata/spark/README.md").flatMap(_.split(" ")).filter(_.nonEmpty).map((_,1)).reduceByKey(_+_)/<code>
![Spark詞頻前十的統計練習](http://p2.ttnews.xyz/loading.gif)
<code>reduceByKeyRDD.sortBy(t => t._2,ascending=false)/<code>
![Spark詞頻前十的統計練習](http://p2.ttnews.xyz/loading.gif)
<code>reduceByKeyRDD.sortBy(t => t._2,ascending=false).take(10)/<code>
sortBy函數:第一個匿名函數表示按照元組的第二個元素進行排序,ascending=false表示按照降序排序,如果不指定這個參數,默認是升序的排序
<code>reduceByKeyRDD.sortBy(t => t._2 * -1).take(10)/<code>
也實現了降序排列,提取TOP10
下面這個方法也可以
<code>reduceByKeyRDD.map(t => t.swap).sortByKey(ascending=false).map(t => t.swap).take(10)/<code>
分解看下:
<code>reduceByKeyRDD.map(t => t.swap).sortByKey(ascending=false).
t.swap :("the",22) --> (22,"the") --> ("the",22)/<code>
<code>reduceByKeyRDD.map(t => t.swap).sortByKey(ascending=false).map(t => t.swap).take(10)/<code>
下面這個性能會更好:
<code>reduceByKeyRDD.map(t => t.swap).sortByKey(ascending=false).take(10).map(t => t.swap)/<code>
用top(10)代替sortByKey(ascending=false).take(10)這一部分
<code>reduceByKeyRDD.map(t => t.swap).top(10).map(t => t.swap)/<code>
閱讀更多 分享電腦學習 的文章