Spark 例子: 寻找文件中前十的数 寻找个数为前十的单词
Henvealf/文
寻找文件中前十的数
样例数据:
123
23
4
977
456
qwe
213
678
其中 “qwe” 为错误数据。
- 生成一个用于匹配数字的正则表达式:
scala> val regex = """^\d+$""".r
regex: scala.util.matching.Regex = ^\d+$
- 然后使用 SortBy 进行排序,注意刚开始过滤了错误数据与去重。
scala> numberRDD.filter(regex.findFirstMatchIn(_) != None).distinct().sortBy(a => a.toInt, false).take(10)
res35: Array[String] = Array(5656, 5646, 5487, 5453, 4543, 4324, 3648, 3548, 3453, 984)
寻找个数为前十的单词
样例数据:
hello
hello
int
end
along
world
world
首先把每个元素 map 成键值对,按 Key 进行加和计数,这时 value 就是每个单词的数目了,之后倒换键值对,倒换后按 key 进行排序,取前10后,再倒换回来。
scala> wordRdd.map(a => (a,1)).reduceByKey((a, b) => (a + b)).map(a =>(a._2,a._1)).sortByKey(false).take(10).map(a =>(a._2,a._1))
res28: Array[(String, Int)] = Array((hello,7), (can,3), (intel,3), (if,3), (to,3), (haha,2), (vim,2), (we,2), (begin,2), (end,2))
End!!