groupByKey 和reduceByKey 的区别

spark groupByKey和groupBy,groupByKey和reduceByKey的区别 groupByKey、groupBy、reduceByKey的区别介绍 阅读详情
一、首先他们都是要经过shuffle的,groupByKey在方法shuffle之间不会合并原样进行shuffle,。reduceByKey进行shuffle之前会先做合并,这样就减少了shuffle的io传送,所以效率高一点。
案例:
object GroupyKeyAndReduceByKeyDemo {
  def main(args: Array[String]): Unit = {
    Logger.getLogger("org").setLevel(Level.WARN)
    val config = new SparkConf().setAppName("GroupyKeyAndReduceByKeyDemo").setMaster("local")
    val sc = new SparkContext(config)
    val arr = Array("val config", "val arr")
    val socketDS = sc.parallelize(arr).flatMap(_.split(" ")).map((_, 1))
    //groupByKey 和reduceByKey 的区别:
    //他们都是要经过shuffle的,groupByKey在方法shuffle之间不会合并原样进行shuffle,
    //reduceByKey进行shuffle之前会先做合并,这样就减少了shuffle的io传送,所以效率高一点
    socketDS.groupByKey().map(tuple => (tuple._1, tuple._2.sum)).foreach(x => {
      println(x._1 + " " + x._2)
    })
    println("----------------------")
    socketDS.reduceByKey(_ + _).foreach(x => {
      println(x._1 + " " + x._2)
    })
    sc.stop()
  }
}
二 、首先groupByKey有三种

查看源码groupByKey()实现了 groupByKey(defaultPartitioner(self))
/**
   * Group the values for each key in the RDD into a single sequence. Hash-partitions the
   * resulting RDD with the existing partitioner/parallelism level. The ordering of elements
   * within each group is not guaranteed, and may even differ each time the resulting RDD is
   * evaluated.
   *
   * @note This operation may be very expensive. If you are grouping in order to perform an
   * aggregation (such as a sum or average) over each key, using `PairRDDFunctions.aggregateByKey`
   * or `PairRDDFunctions.reduceByKey` will provide much better performance.
   */
  def groupByKey(): RDD[(K, Iterable[V])] = self.withScope {
    groupByKey(defaultPartitioner(self))
  }

查看源码 groupByKey(numPartitions: Int) 实现了 groupByKey(new HashPartitioner(numPartitions))

/**
   * Group the values for each key in the RDD into a single sequence. Hash-partitions the
   * resulting RDD with into `numPartitions` partitions. The ordering of elements within
   * each group is not guaranteed, and may even differ each time the resulting RDD is evaluated.
   *
   * @note This operation may be very expensive. If you are grouping in order to perform an
   * aggregation (such as a sum or average) over each key, using `PairRDDFunctions.aggregateByKey`
   * or `PairRDDFunctions.reduceByKey` will provide much better performance.
   *
   * @note As currently implemented, groupByKey must be able to hold all the key-value pairs for any
   * key in memory. If a key has too many values, it can result in an `OutOfMemoryError`.
   */
  def groupByKey(numPartitions: Int): RDD[(K, Iterable[V])] = self.withScope {
    groupByKey(new HashPartitioner(numPartitions))
  }

其实上面两个都是实现了groupByKey(partitioner: Partitioner)

/**
   * Group the values for each key in the RDD into a single sequence. Allows controlling the
   * partitioning of the resulting key-value pair RDD by passing a Partitioner.
   * The ordering of elements within each group is not guaranteed, and may even differ
   * each time the resulting RDD is evaluated.
   *
   * @note This operation may be very expensive. If you are grouping in order to perform an
   * aggregation (such as a sum or average) over each key, using `PairRDDFunctions.aggregateByKey`
   * or `PairRDDFunctions.reduceByKey` will provide much better performance.
   *
   * @note As currently implemented, groupByKey must be able to hold all the key-value pairs for any
   * key in memory. If a key has too many values, it can result in an `OutOfMemoryError`.
   */
  def groupByKey(partitioner: Partitioner): RDD[(K, Iterable[V])] = self.withScope {
    // groupByKey shouldn't use map side combine because map side combine does not
    // reduce the amount of data shuffled and requires all map side data be inserted
    // into a hash table, leading to more objects in the old gen.
    val createCombiner = (v: V) => CompactBuffer(v)
    val mergeValue = (buf: CompactBuffer[V], v: V) => buf += v
    val mergeCombiners = (c1: CompactBuffer[V], c2: CompactBuffer[V]) => c1 ++= c2
    val bufs = combineByKeyWithClassTag[CompactBuffer[V]](
      createCombiner, mergeValue, mergeCombiners, partitioner, mapSideCombine = false)
    bufs.asInstanceOf[RDD[(K, Iterable[V])]]
  }
而groupByKey(partitioner: Partitioner)有实现了combineByKeyWithClassTag,所以可以说groupByKey其实底层都是combineByKeyWithClassTag的实现,只是实现的方式不同。


三、再查看reduceByKey也有三种方式


/**
   * Merge the values for each key using an associative and commutative reduce function. This will
   * also perform the merging locally on each mapper before sending results to a reducer, similarly
   * to a "combiner" in MapReduce. Output will be hash-partitioned with the existing partitioner/
   * parallelism level.
   */
  def reduceByKey(func: (V, V) => V): RDD[(K, V)] = self.withScope {
    reduceByKey(defaultPartitioner(self), func)
  }
/**
   * Merge the values for each key using an associative and commutative reduce function. This will
   * also perform the merging locally on each mapper before sending results to a reducer, similarly
   * to a "combiner" in MapReduce. Output will be hash-partitioned with numPartitions partitions.
   */
  def reduceByKey(func: (V, V) => V, numPartitions: Int): RDD[(K, V)] = self.withScope {
    reduceByKey(new HashPartitioner(numPartitions), func)
  }
/**
   * Merge the values for each key using an associative and commutative reduce function. This will
   * also perform the merging locally on each mapper before sending results to a reducer, similarly
   * to a "combiner" in MapReduce.
   */
  def reduceByKey(partitioner: Partitioner, func: (V, V) => V): RDD[(K, V)] = self.withScope {
    combineByKeyWithClassTag[V]((v: V) => v, func, func, partitioner)
  }
通过查看这三种reduceByKey不难发现,前两种是最后一种的实现。而最后一种是又实现了combineByKeyWithClassTag。

### groupByKey是这样实现的

combineByKeyWithClassTag[CompactBuffer[V]](createCombiner, mergeValue, mergeCombiners, partitioner, mapSideCombine = false)

### reduceByKey是这样实现的
combineByKeyWithClassTag[V]((v: V) => v, func, func, partitioner)

对比上面发现,groupByKey设置了mapSideCombine = false,在map端不进行合并,那就是在shuffle前不合并。而reduceByKey没有设置

难道reduceByKey默认合并吗????

四、接下来,我们仔细看一下combineByKeyWithClassTag
/**
   * :: Experimental ::
   * Generic function to combine the elements for each key using a custom set of aggregation
   * functions. Turns an RDD[(K, V)] into a result of type RDD[(K, C)], for a "combined type" C
   *
   * Users provide three functions:
   *
   *  - `createCombiner`, which turns a V into a C (e.g., creates a one-element list)
   *  - `mergeValue`, to merge a V into a C (e.g., adds it to the end of a list)
   *  - `mergeCombiners`, to combine two C's into a single one.
   *
   * In addition, users can control the partitioning of the output RDD, and whether to perform
   * map-side aggregation (if a mapper can produce multiple items with the same key).
   *
   * @note V and C can be different -- for example, one might group an RDD of type
   * (Int, Int) into an RDD of type (Int, Seq[Int]).
   */
  @Experimental
  def combineByKeyWithClassTag[C](
      createCombiner: V => C,
      mergeValue: (C, V) => C,
      mergeCombiners: (C, C) => C,
      partitioner: Partitioner,
      mapSideCombine: Boolean = true,
      serializer: Serializer = null)(implicit ct: ClassTag[C]): RDD[(K, C)] = self.withScope {
    require(mergeCombiners != null, "mergeCombiners must be defined") // required as of Spark 0.9.0
    if (keyClass.isArray) {
      if (mapSideCombine) {
        throw new SparkException("Cannot use map-side combining with array keys.")
      }
      if (partitioner.isInstanceOf[HashPartitioner]) {
        throw new SparkException("HashPartitioner cannot partition array keys.")
      }
    }
    val aggregator = new Aggregator[K, V, C](
      self.context.clean(createCombiner),
      self.context.clean(mergeValue),
      self.context.clean(mergeCombiners))
    if (self.partitioner == Some(partitioner)) {
      self.mapPartitions(iter => {
        val context = TaskContext.get()
        new InterruptibleIterator(context, aggregator.combineValuesByKey(iter, context))
      }, preservesPartitioning = true)
    } else {
      new ShuffledRDD[K, V, C](self, partitioner)
        .setSerializer(serializer)
        .setAggregator(aggregator)
        .setMapSideCombine(mapSideCombine)
    }
  }
通过查看combineByKeyWithClassTag的,发现reduceByKey默认在map端进行合并,那就是在shuffle前进行合并,如果合并了一些数据,那在shuffle时进行溢写则减少了磁盘IO,所以reduceByKey会快一些。

spark中reduceByKey、groupByKey、combineByKey的区别 reduceByKey reduceByKey用于对每个key对应的多个value进行merge操作,最重要的是它能够在本地先进行merge操作,并且merge操作可以通过函数自定义; groupByKey groupByKey也是对每个key进行操作,但只生成一个sequence,groupByKey本身不能自定义函数,需要先生成RDD,然后才能对此RDD通过map进行自定义函数操作 比较发... 阅读详情

相关推荐

Power BI实战:从数据清洗到可视化报表的完整流程

本文详细介绍了使用Power BI进行数据分析的完整流程,从数据获取、清洗整理到建模与可视化。通过实战案例,重点讲解了连接MySQL数据库、使用Power Query进行数据清洗、利用DAX创建核心度量值以及设计交互式报表的关键步骤与技巧,帮助用户高效完成从原始数据到专业可视化报表的转化,实现数据驱动决策。

weixin_29070721的博客 398

一文看懂Spark中reduceByKey 和 groupByKey 的区别

目录 一、先看结论 二、举例、画图说明 1.实现的功能分别是什么? 1).groupByKey 实现 WordCount 2).reduceByKey 实现 WordCount 2.画图解析两种实现方式的区别 1) groupByKey 实现 WordCount 2).reduceByKey 实现 WordCount(简单流程) 3).reduceByKey 实现 WordCount(终极流程) 一、先看结论 1.从Shuffle的角度 reduceByKey 和 g...

TRX的博客 1万+

S32K3基于EB配置GPT触发WDG的实战解析

本文详细解析了S32K3 MCU基于EB tresos工具配置GPT定时器触发看门狗(WDG)的实战方法。通过分析协同工作机制、MCAL配置步骤及代码实现,帮助开发者构建可靠的硬件监控系统,提升汽车电子系统的安全性与实时性。

f9g0h的博客 205

Spark中reduceByKey 和 groupByKey 的区别 [超级详细]

Spark中reduceByKey 和 groupByKey 的区别 [超级详细]

weixin_42326851的博客 1992

搞定8GB/s数据流:一个FPGA工程师的XDMA驱动调优实战(附避坑清单)

本文详细记录了FPGA工程师在XDMA驱动调优过程中实现8GB/s高带宽数据流的实战经验。通过优化DDR访问、中断响应、DMA映射等关键环节,解决了PCIE数据采集卡在高带宽场景下的性能瓶颈,并提供了实用的避坑清单和技术方案。

weixin_29194255的博客 203

APM 飞行模式切换--源码详解

APM飞控中有很多种方式可以改变飞行模式。其中最常见的为遥控器切换和地面站切换两种方式。 下面以遥控器切换为例详解飞行模式切换逻辑。 APM遥控器切换飞行模式的源代码在RC_Channel.cpp文件中的RC_Channel_Copter::do_aux_function_change_mode()函数中。 const bool success = copter.set_mode()调用Copter::set_mode()函数,在set_mode()函数中调用mode_fro...

qq_30623591的博客 2440

reduceByKey(_+_)

reduceByKey

bitmao888的博客 708

Ubuntu系统下STM32开发环境搭建:从零配置CubeMX、VSCode与OpenOCD调试实战

本文详细介绍了在Ubuntu系统下搭建STM32开发环境的完整流程,包括CubeMX、VSCode和OpenOCD的安装配置。通过实战教程指导开发者从基础环境准备到工程创建与调试,提供高效的嵌入式开发解决方案,并分享常见问题解决方法。

potato的博客 941

Spark中reduceByKey(_+_)的说明

https://blog.youkuaiyun.com/CDW2328/article/details/90319420

Gloria的博客 2400

动态博弈、威胁与承诺(博弈论入门学习笔记四)

0 动态博弈 动态博弈:行动有先后顺序,不同的参与人在不同时点行动,先行动者的选择影响后行动者的选择空间,后行动者可以观察到先行动者做了什么选择。例如下棋、消费者和商家讨价还价、谈婚论嫁、企业之间的价格战等等。 因此,为了做出最优的行动选择,每个参与人都应该思考:如果我如此选择,对方将如何应对?如果我是他,我将会如何行动?给定他的应对,什么是我的最优选择? 动态博弈中的战略:在博弈开始之前就...

stepho的博客 1万+

xilinx原语及bank简介

图8是HP bank与HR bank的IO模块,其中PAD是FPGA的金属管脚,IOB是输入、输出引脚的控制模块。此时使用原语就可以只调用需要的组件,不需要去考虑其余组件参数设置,就方便很多,借助此次机会就对IDDR、ODDR、IDELAYE2、ODELAYE2、IDELAYCRTL、ISERDESE、OSERDESE等几个原语做了简要了解,并对原语的各个模式进行了仿真,本文最初是介绍IDDR的,但在介绍IDDR这些原语之前,还需要了解一下7系列FPGA bank的分类和区别,所以就有了本文。

qq_43416206的博客 413

Spark源码之reduceByKey与GroupByKey

Spark中针对键值对类型的RDD做各种操作比较常用的两个方法就是ReduceByKey与GroupByKey方法,下面从源码里面看看ReduceByKey与GroupByKey方法的使用以及内部逻辑。官方源码解释:三种形式的reduceByKey总体来说下面三种形式的方法备注大意为: 根据用户传入的函数来对(K,V)中每个K对应的所有values做merge操作(具体的操作类型根据用户定义的函数

学习,我们是认真的 1万+

Transformer大模型实战 文本摘要任务

Transformer, 文本摘要, 自然语言处理, 预训练模型, 序列到序列, BERT, BART, T5 1. 背景介绍 文本摘要任务是自然语言处理 (NLP) 领域的重要研究方向之一,旨在从长篇文本中提取关键信息,生成简洁、准确的摘要。随着深度学习技术的快速发展,基于 Tra

AI大模型应用之禅 1340

spark中groupByKey 和reduceByKey 的区别:

他们都是要经过shuffle的,groupByKey在方法shuffle之间不会合并原样进行shuffle,。reduceByKey进行shuffle之前会先做合并,这样就减少了shuffle的io传送,所以效率高一点。object GroupyKeyAndReduceByKeyDemo { def main(args: Array[String]): Unit = { Logg

qq_38799155的博客 4673

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

reduceByKey和groupByKey区别与用法

转载原文地址:https://blog.youkuaiyun.com/weixin_41804049/article/details/80373741 在spark中,我们知道一切的操作都是基于RDD的。在使用中,RDD有一种非常特殊也是非常实用的format——pair RDD,即RDD的每一行是(key, value)的格式。这种格式很像Python的字典类型,便于针对key进行一些处理。 针对...

u010476994的博客 1万+

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

reduceByKey、groupByKey、aggregateByKey区别及用法

reduceByKey、groupByKey、aggregateByKey区别及用法参考官网介绍使用方法数据准备具体算子使用reduceByKey、groupByKey、aggregateByKey区别reduceByKeygroupByKeyaggregateByKey 参考官网介绍 reduceByKey(func, [numPartitions]) 当在 (K, V) 对的数据集上调用时,返回 (K, V) 对的数据集,其中每个键的值使用给定的 reduce 函数func聚合,该函数必须是 (V,

qq_39565127的博客 1691

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

reduceByKey和groupByKey的区别:

spark中reduceByKey和groupByKey的区别: 打开源码查看英文解释: /** * Merge the values for each key using an associative reduce function. This will also perform * the merging locally on each mapper before sending re...

fa124607857的博客 633

spark 算子之 reduceByKey与groupByKey的区别

补充:reduceByKey与groupByKey的区别? [优化代码的最基本思路](1)当采用reduceByKeyt时,Spark可以在每个分区移动数据之前将待输出数据与一个共用的key结合。借助下图可以理解在reduceByKey里究竟发生了什么。 注意在数据对被搬移前同一机器上同样的key是怎样被组合的(reduceByKey中的lamdba函数)。然后lamdba函数在每个区上被再次调用...

wjl7813的博客 1807

spark算子中reduceByKey和groupByKey两者的区别

spark中算子应该是重点中的重点了,今天我们来分析一下两个算子reduceByKey和groupByKey 这两个算子都属于k-v类型的算子 我们先来看看这两个算子的作用是什么? reduceByKey是通过key对数据进行聚合 groupByKey是通过key对数据进行分组 这两个都需要对数据进行打乱重组,所以都会有shuffle 两者的区别: reduceByKey:在shuffle之前有combine(预聚合)操作,返回结果是RDD[k,v]。 groupByKey:直接进行shuffle。 我

newhandnew413的博客 1972

reduceByKey 和 groupByKey的区别

reduceByKey 和 groupByKey的区别

A1328042201的博客 469

Spark rdd之groupByKey & reduceByKey 区别

groupByKey 和 reduceByKey 有什么区别? 从这两个算子的字面意思来看,groupByKey 是先按照 key 进行分组,然后把相同的 key 收集到一起;reduceByKey( f ),把相同的 key 进行聚合,聚合的逻辑由传入 f 函数所指定。 这两个算子,只针对 kv 格式的 RDD 才能使用。在前几篇文章中说了,每调一个算子,都是一次 RDD 的转换,也是一次数据形态的转换。 既然有 RDD 的转换,那么就会有数据依赖形成。下面分别来看看它们所形成的数据依赖图。 1 redu

南风知我意 1285

reduceByKey、groupByKey以及combineByKey的区别

概述:这三种算子在spark中用的比较多。 reduceByKey: 是对key的value进行merge操作,在一个(K,V)的RDD上调用,返回一个(K,V)的RDD,使用指定的reduce函数,将相同key的值聚合到一起,与groupByKey类似,reduce任务的个数可以通过第二个可选的参数来设置,最重要的是它能够在本地先进行merge操作,并且merge操作可以通过函数自定义; gr...

murphyZ的博客 778

reduceByKey和groupByKey的区别

reduceByKey:按照key进行聚合,在shuffle之前有combine(预聚合)操作,返回结果是RDD[k,v]. groupByKey:按照key进行分组,直接进行shuffle。 开发指导:reduceByKey比groupByKey,建议使用。但是需要注意是否会影响业务逻辑。 ...

weixin_43548518的博客 4494
上一篇: Spark-Streaming的window滑动窗口及热点搜索词统计案例
下一篇: Spark-Streaming之transform操作,实时黑名单过滤案例
守猫de人
博客等级 码龄10年 29粉丝 46原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值