輸入:java
hello tom hello jerry hello kitty hello world hello tom
讀取 HDFS 中位於 hdfs://node1:9000/wc/input 目錄下的文本文件, 讀取結果賦值給 textRddnode
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) 排序spa
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) 排序(字典順序)的 WordCountscala
思路: 在 wcRdd 的基礎上對 Key(word) 排序code
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 操做:orm
使用 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) 排序(降序)的 WordCountinput
思路1: 在 wcRdd 的基礎上, 先把K(word), V(count)反轉, 此時對Key(count)進行排序, 最後再反轉回去it
// 在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() 操做form
// _._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 也能夠寫出新花樣