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")

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) 排序

var sortByWordRdd = wcRdd.sortByKey(true)    // 在 wcRdd 的基础上对 Key(word) 排序
sortByWordRdd.collect
res3: Array[(String, Int)] = Array((hello,5), (jerry,1), (kitty,1), (tom,2), (world,1))

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

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

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

Spark + Scala = 快速 + 高效,  WordCount 也可以写出新花样

你可能感兴趣的:(spark,wordcount,spark-shell)