[Spark Core] Spark Shell 实现 Word Count


 

  0. 说明

  在 Spark Shell 实现 Word Count

  RDD (Resilient Distributed dataset), 弹性分布式数据集。

 

  示意图

 

 


 

  1. 实现

  1.1 分步实现

# step 1 加载文档
val rdd1 = sc.textFile("file:///home/centos/wc1.txt")

# step 2 压扁
val rdd2 = rdd1.flatMap(line=>{line.split(" ")})

# step 3 标1成对
val rdd3 = rdd2.map(word=>{(word , 1)})

# step 4 聚合
val rdd4 = rdd3.reduceByKey((a:Int,b:Int)=>{a + b})

# step 5
rdd4.collect()

  

 

  1.2 一步完成 (reduceByKey)

sc.textFile("file:///home/centos/wc1.txt").flatMap(_.split(" ")).map((_,1)).reduceByKey(_+_).collect()

 


  1.3 一步完成 (groupByKey)

sc.textFile("file:///home/centos/wc1.txt").flatMap(_.split(" ")).map((_,1)).groupByKey().mapValues(_.size).collect()

 

 


 

posted @ 2018-10-08 19:35  山间一棵松  阅读(273)  评论(0编辑  收藏  举报