久久精品人人爽,华人av在线,亚洲性视频网站,欧美专区一二三

spark

173次閱讀
沒有評論

共計 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)知識。

正文完
 
丸趣
版權(quán)聲明:本站原創(chuàng)文章,由 丸趣 2023-08-25發(fā)表,共計1728字。
轉(zhuǎn)載說明:除特殊說明外本站除技術(shù)相關(guān)以外文章皆由網(wǎng)絡(luò)搜集發(fā)布,轉(zhuǎn)載請注明出處。
評論(沒有評論)
主站蜘蛛池模板: 井陉县| 铜川市| 册亨县| 尖扎县| 姚安县| 读书| 通江县| 习水县| 西安市| 安福县| 北辰区| 金昌市| 桓台县| 竹北市| 五指山市| 永康市| 班戈县| 霍州市| 蕉岭县| 寻甸| 广水市| 绥德县| 陈巴尔虎旗| 顺昌县| 东安县| 南部县| 大连市| 湾仔区| 体育| 洪泽县| 桐乡市| 南汇区| 枞阳县| 塔河县| 金坛市| 拉萨市| 灵宝市| 泰州市| 前郭尔| 营山县| 平乡县|