栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

【Spark】WordCount的多种实现方式

【Spark】WordCount的多种实现方式

WordCount的多种实现方式
  • 准备工作
  • 使用groupBy
  • 使用groupByKey
  • 使用reduceByKey
  • 使用aggregateByKey
  • 使用foldByKey
  • 使用combineByKey
  • 使用countByKey
  • 使用countByValue

准备工作

查看数据

创建SparkContext

  val spark = new SparkConf().setMaster("local[6]").setAppName("wordCount")
  val sc = new SparkContext(spark)
  val rdd = sc.textFile("data/wordcount.txt")
使用groupBy
  
  @Test
  def test1():Unit = {
    rdd.flatMap(_.split(" "))
      .groupBy(word => word)
      .mapValues(_.size)
      .collect()
      .foreach(println(_))
  }
使用groupByKey

效率不高

  
  @Test
  def groupByKey():Unit = {
    rdd.flatMap(_.split(" "))
      .map((_,1))
      .groupByKey()
      .mapValues(_.size)
      .collect()
      .foreach(println(_))
  }
使用reduceByKey
  
  @Test
  def reduceByKey():Unit = {
    rdd.flatMap(_.split(" "))
      .map((_,1))
      .reduceByKey(_+_)
      .collect()
      .foreach(println(_))
  }
使用aggregateByKey
  
  @Test
  def aggregateByKey():Unit = {
    rdd.flatMap(_.split(" "))
      .map((_,1))
      .aggregateByKey(0)(_+_,_+_)
      .collect()
      .foreach(println(_))
  }
使用foldByKey
  
  @Test
  def foldByKey():Unit = {
    rdd.flatMap(_.split(" "))
      .map((_,1))
      .foldByKey(0)(_+_)
      .collect()
      .foreach(println(_))
  }
使用combineByKey
  
  @Test
  def combineByKey(): Unit = {
    rdd.flatMap(_.split(" "))
      .map((_, 1))
      .combineByKey(
        v => v,
        (x: Int, y) => x + y,
        (x: Int, y: Int) => x + y
      )
      .collect()
      .foreach(println(_))
  }
使用countByKey
  
  @Test
  def countByKey(): Unit = {
    rdd.flatMap(_.split(" "))
      .map((_, 1))
      .countByKey()
  }
使用countByValue
  
  @Test
  def countByvalue(): Unit = {
    rdd.flatMap(_.split(" "))
      .countByValue()
  }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/696214.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号