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 + Scala = 快速 + 高效,  WordCount 也可以写出新花样

转载于:https://my.oschina.net/u/2503731/blog/665489

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值