spark-shell实现WordCount&按word排序&按count排序

发布时间:2021-11-24 16:03:13 作者:柒染
来源:亿速云 阅读:256

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排序问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

推荐阅读:
  1. Python3实现快速排序、归并排序、堆排序
  2. python如何实现排序

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spark-shell wordcount

上一篇:Java15有什么新特性

下一篇:JAVA怎么去掉Excel中的对象

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》