spark

65次阅读
没有评论

共计 1728 个字符,预计需要花费 5 分钟才能阅读完成。

spark-shell 实现 WordCount 按 word 排序 按 count 排序,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

输入:

hello tom
hello jerry
hello kitty
hello world
hello tom

读取 HDFS 中位于 hdfs://node1:9000/wc/input 目录下的文本文件, 读取结果赋值给 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)

实现普通的 WordCount, 但结果不会像 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))

实现按  Key(word)  排序 (字典顺序) 的  WordCount

思路:  在 wcRdd 的基础上对 Key(word) 排序

val sortByWordRdd = wcRdd.sortByKey(true) //  在  wcRdd  的基础上对  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 项,  就是  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))

实现按  Value(count)  排序 (降序) 的  WordCount

思路 1:  在 wcRdd 的基础上, 先把 K(word), V(count)反转, 此时对 Key(count)进行排序, 最后再反转回去

//  在 wcRdd 的基础上,  先把 K(word), V(count)反转,  此时对 Key(count)进行排序,  最后再反转回去
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 项,  就是  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))

关于 spark-shell 实现 WordCount 按 word 排序 按 count 排序问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注丸趣 TV 行业资讯频道了解更多相关知识。

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-08-25发表,共计1728字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)