共計 1728 個字符,預(yù)計需要花費(fèi) 5 分鐘才能閱讀完成。
spark-shell 實(shí)現(xiàn) WordCount 按 word 排序 按 count 排序,針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
輸入:
hello tom
hello jerry
hello kitty
hello world
hello tom
讀取 HDFS 中位于 hdfs://node1:9000/wc/input 目錄下的文本文件, 讀取結(jié)果賦值給 textRdd
val textRdd = sc.textFile(hdfs://node1:9000/wc/input)
textRdd.collect
res1: Array[String] = Array(hello,tom, hello,jerry, hello,kitty, hello,world, hello,tom)
實(shí)現(xiàn)普通的 WordCount, 但結(jié)果不會像 MapReduce 那樣按 Key(word) 排序
val wcRdd = textRdd.flatMap(_.split( )).map((_, 1)).reduceByKey(_ + _)
wcRdd.collect
res2: Array[(String, Int)] = Array((tom,2), (hello,5), (jerry,1), (kitty,1), (world,1))
實(shí)現(xiàn)按 Key(word) 排序 (字典順序) 的 WordCount
思路: 在 wcRdd 的基礎(chǔ)上對 Key(word) 排序
val sortByWordRdd = wcRdd.sortByKey(true) // 在 wcRdd 的基礎(chǔ)上對 Key(word) 排序
sortByWordRdd.collect
res3: Array[(String, Int)] = Array((hello,5), (jerry,1), (kitty,1), (tom,2), (world,1))
在 Spark 1.3 中, 可以使用這樣一個 RDD 的 transform 操作:
使用 sortBy() 操作
// _._1 : 元組的第 1 項(xiàng), 就是 word; true : 按升序排序
val sortByWordRdd = wcRdd.sortBy(_._1, true)
sortByWordRdd.collect
res3: Array[(String, Int)] = Array((hello,5), (jerry,1), (kitty,1), (tom,2), (world,1))
實(shí)現(xiàn)按 Value(count) 排序 (降序) 的 WordCount
思路 1: 在 wcRdd 的基礎(chǔ)上, 先把 K(word), V(count)反轉(zhuǎn), 此時對 Key(count)進(jìn)行排序, 最后再反轉(zhuǎn)回去
// 在 wcRdd 的基礎(chǔ)上, 先把 K(word), V(count)反轉(zhuǎn), 此時對 Key(count)進(jìn)行排序, 最后再反轉(zhuǎn)回去
val sortByCountRdd = wcRdd.map(x = (x._2,x._1)).sortByKey(false).map(x = (x._2,x._1))
sortByCountRdd.collect
res4: Array[(String, Int)] = Array((hello,5), (tom,2), (jerry,1), (kitty,1), (world,1))
思路 2: 直接使用 sortBy() 操作
// _._2 : 元組的第 2 項(xiàng), 就是 count; false : 按降序排序
val sortByCountRdd = wcRdd.sortBy(_._2, false)
sortByCountRdd.collect
res4: Array[(String, Int)] = Array((hello,5), (tom,2), (jerry,1), (kitty,1), (world,1))
關(guān)于 spark-shell 實(shí)現(xiàn) WordCount 按 word 排序 按 count 排序問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注丸趣 TV 行業(yè)資訊頻道了解更多相關(guān)知識。