reduceByKey和groupByKey区别与用法

Spark算子reduceByKey深度解析 最近经常使用到reduceByKey这个算子,懵逼的时间占据多数,所以沉下心来翻墙上国外的帖子仔细过了一遍,发现一篇不错的,在此加上个人的理解整体过一遍这个算子,那么我们开始: 国外的大牛一上来给出这么一句话,个人感觉高度概括了reduceByKey的功能:Spark RDD reduceByKey function merges the values for each key using 阅读详情

转载原文地址:https://blog.csdn.net/weixin_41804049/article/details/80373741

在spark中,我们知道一切的操作都是基于RDD的。在使用中,RDD有一种非常特殊也是非常实用的format——pair RDD,即RDD的每一行是(key, value)的格式。这种格式很像Python的字典类型,便于针对key进行一些处理。

 

针对pair RDD这样的特殊形式,spark中定义了许多方便的操作,今天主要介绍一下reduceByKey和groupByKey,因为在接下来讲解《在spark中如何实现SQL中的group_concat功能?》时会用到这两个operations。

 

首先,看一看spark官网[1]是怎么解释的:

reduceByKey(func, numPartitions=None)

 

Merge the values for each key using an associative reduce function. This will also perform the merginglocally on each mapper before sending results to a reducer, similarly to a “combiner” in MapReduce. Output will be hash-partitioned with numPartitions partitions, or the default parallelism level if numPartitions is not specified.

也就是,reduceByKey用于对每个key对应的多个value进行merge操作,最重要的是它能够在本地先进行merge操作,并且merge操作可以通过函数自定义。

groupByKey(numPartitions=None)

 

Group the values for each key in the RDD into a single sequence. Hash-partitions the resulting RDD with numPartitions partitions. Note: If you are grouping in order to perform an aggregation (such as a sum or average) over each key, using reduceByKey or aggregateByKey will provide much better performance.

也就是,groupByKey也是对每个key进行操作,但只生成一个sequence。需要特别注意“Note”中的话,它告诉我们:如果需要对sequence进行aggregation操作(注意,groupByKey本身不能自定义操作函数),那么,选择reduceByKey/aggregateByKey更好。这是因为groupByKey不能自定义函数,我们需要先用groupByKey生成RDD,然后才能对此RDD通过map进行自定义函数操作。

 

为了更好的理解上面这段话,下面我们使用两种不同的方式去计算单词的个数[2]:

 

[java] view plain copy

  1. val words = Array("one", "two", "two", "three", "three", "three")  
  2.   
  3. val wordPairsRDD = sc.parallelize(words).map(word => (word, 1))  
  4.   
  5. val wordCountsWithReduce = wordPairsRDD.reduceByKey(_ + _)  
  6.   
  7. val wordCountsWithGroup = wordPairsRDD.groupByKey().map(t => (t._1, t._2.sum))  

上面得到的wordCountsWithReduce和wordCountsWithGroup是完全一样的,但是,它们的内部运算过程是不同的。

 

 

(1)当采用reduceByKeyt时,Spark可以在每个分区移动数据之前将待输出数据与一个共用的key结合。借助下图可以理解在reduceByKey里究竟发生了什么。 注意在数据对被搬移前同一机器上同样的key是怎样被组合的(reduceByKey中的lamdba函数)。然后lamdba函数在每个区上被再次调用来将所有值reduce成一个最终结果。整个过程如下:

 

(2)当采用groupByKey时,由于它不接收函数,spark只能先将所有的键值对(key-value pair)都移动,这样的后果是集群节点之间的开销很大,导致传输延时。整个过程如下:

因此,在对大数据进行复杂计算时,reduceByKey优于groupByKey。

另外,如果仅仅是group处理,那么以下函数应该优先于 groupByKey :
  (1)、combineByKey 组合数据,但是组合之后的数据类型与输入时值的类型不一样。
  (2)、foldByKey合并每一个 key 的所有值,在级联函数和“零值”中使用。

 

最后,对reduceByKey中的func做一些介绍:

如果是用Python写的spark,那么有一个库非常实用:operator[3],其中可以用的函数包括:大小比较函数,逻辑操作函数,数学运算函数,序列操作函数等等。这些函数可以直接通过“from operator import *”进行调用,直接把函数名作为参数传递给reduceByKey即可。如下:

 

[python] view plain copy

  1. <span style="font-size:14px;">from operator import add  
  2. rdd = sc.parallelize([("a", 1), ("b", 1), ("a", 1)])  
  3. sorted(rdd.reduceByKey(add).collect())  
  4.   
  5. [('a', 2), ('b', 1)]</span>  

 

下面是附加源码更加详细的解释

转自:https://blog.csdn.net/ZMC921/article/details/75098903

 

一、首先他们都是要经过shuffle的,groupByKey在方法shuffle之间不会合并原样进行shuffle,。reduceByKey进行shuffle之前会先做合并,这样就减少了shuffle的io传送,所以效率高一点。

案例:

[plain] view plain copy

 

  1. object GroupyKeyAndReduceByKeyDemo {  
  2.   def main(args: Array[String]): Unit = {  
  3.     Logger.getLogger("org").setLevel(Level.WARN)  
  4.     val config = new SparkConf().setAppName("GroupyKeyAndReduceByKeyDemo").setMaster("local")  
  5.     val sc = new SparkContext(config)  
  6.     val arr = Array("val config", "val arr")  
  7.     val socketDS = sc.parallelize(arr).flatMap(_.split(" ")).map((_, 1))  
  8.     //groupByKey 和reduceByKey 的区别:  
  9.     //他们都是要经过shuffle的,groupByKey在方法shuffle之间不会合并原样进行shuffle,  
  10.     //reduceByKey进行shuffle之前会先做合并,这样就减少了shuffle的io传送,所以效率高一点  
  11.     socketDS.groupByKey().map(tuple => (tuple._1, tuple._2.sum)).foreach(x => {  
  12.       println(x._1 + " " + x._2)  
  13.     })  
  14.     println("----------------------")  
  15.     socketDS.reduceByKey(_ + _).foreach(x => {  
  16.       println(x._1 + " " + x._2)  
  17.     })  
  18.     sc.stop()  
  19.   }  
  20. }  

二 、首先groupByKey有三种

查看源码groupByKey()实现了 groupByKey(defaultPartitioner(self))

[java] view plain copy

 

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

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

[java] view plain copy

 

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

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

[java] view plain copy

 

  1. /** 
  2.    * Group the values for each key in the RDD into a single sequence. Allows controlling the 
  3.    * partitioning of the resulting key-value pair RDD by passing a Partitioner. 
  4.    * The ordering of elements within each group is not guaranteed, and may even differ 
  5.    * each time the resulting RDD is evaluated. 
  6.    * 
  7.    * @note This operation may be very expensive. If you are grouping in order to perform an 
  8.    * aggregation (such as a sum or average) over each key, using `PairRDDFunctions.aggregateByKey` 
  9.    * or `PairRDDFunctions.reduceByKey` will provide much better performance. 
  10.    * 
  11.    * @note As currently implemented, groupByKey must be able to hold all the key-value pairs for any 
  12.    * key in memory. If a key has too many values, it can result in an `OutOfMemoryError`. 
  13.    */  
  14.   def groupByKey(partitioner: Partitioner): RDD[(K, Iterable[V])] = self.withScope {  
  15.     // groupByKey shouldn't use map side combine because map side combine does not  
  16.     // reduce the amount of data shuffled and requires all map side data be inserted  
  17.     // into a hash table, leading to more objects in the old gen.  
  18.     val createCombiner = (v: V) => CompactBuffer(v)  
  19.     val mergeValue = (buf: CompactBuffer[V], v: V) => buf += v  
  20.     val mergeCombiners = (c1: CompactBuffer[V], c2: CompactBuffer[V]) => c1 ++= c2  
  21.     val bufs = combineByKeyWithClassTag[CompactBuffer[V]](  
  22.       createCombiner, mergeValue, mergeCombiners, partitioner, mapSideCombine = false)  
  23.     bufs.asInstanceOf[RDD[(K, Iterable[V])]]  
  24.   }  

而groupByKey(partitioner: Partitioner)有实现了combineByKeyWithClassTag,所以可以说groupByKey其实底层都是combineByKeyWithClassTag的实现,只是实现的方式不同。

 

 

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


 

[java] view plain copy

 

  1. /** 
  2.    * Merge the values for each key using an associative and commutative reduce function. This will 
  3.    * also perform the merging locally on each mapper before sending results to a reducer, similarly 
  4.    * to a "combiner" in MapReduce. Output will be hash-partitioned with the existing partitioner/ 
  5.    * parallelism level. 
  6.    */  
  7.   def reduceByKey(func: (V, V) => V): RDD[(K, V)] = self.withScope {  
  8.     reduceByKey(defaultPartitioner(self), func)  
  9.   }  

[java] view plain copy

 

  1. /** 
  2.    * Merge the values for each key using an associative and commutative reduce function. This will 
  3.    * also perform the merging locally on each mapper before sending results to a reducer, similarly 
  4.    * to a "combiner" in MapReduce. Output will be hash-partitioned with numPartitions partitions. 
  5.    */  
  6.   def reduceByKey(func: (V, V) => V, numPartitions: Int): RDD[(K, V)] = self.withScope {  
  7.     reduceByKey(new HashPartitioner(numPartitions), func)  
  8.   }  

[java] view plain copy

 

  1. /** 
  2.    * Merge the values for each key using an associative and commutative reduce function. This will 
  3.    * also perform the merging locally on each mapper before sending results to a reducer, similarly 
  4.    * to a "combiner" in MapReduce. 
  5.    */  
  6.   def reduceByKey(partitioner: Partitioner, func: (V, V) => V): RDD[(K, V)] = self.withScope {  
  7.     combineByKeyWithClassTag[V]((v: V) => v, func, func, partitioner)  
  8.   }  

通过查看这三种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

[java] view plain copy

 

  1. /** 
  2.    * :: Experimental :: 
  3.    * Generic function to combine the elements for each key using a custom set of aggregation 
  4.    * functions. Turns an RDD[(K, V)] into a result of type RDD[(K, C)], for a "combined type" C 
  5.    * 
  6.    * Users provide three functions: 
  7.    * 
  8.    *  - `createCombiner`, which turns a V into a C (e.g., creates a one-element list) 
  9.    *  - `mergeValue`, to merge a V into a C (e.g., adds it to the end of a list) 
  10.    *  - `mergeCombiners`, to combine two C's into a single one. 
  11.    * 
  12.    * In addition, users can control the partitioning of the output RDD, and whether to perform 
  13.    * map-side aggregation (if a mapper can produce multiple items with the same key). 
  14.    * 
  15.    * @note V and C can be different -- for example, one might group an RDD of type 
  16.    * (Int, Int) into an RDD of type (Int, Seq[Int]). 
  17.    */  
  18.   @Experimental  
  19.   def combineByKeyWithClassTag[C](  
  20.       createCombiner: V => C,  
  21.       mergeValue: (C, V) => C,  
  22.       mergeCombiners: (C, C) => C,  
  23.       partitioner: Partitioner,  
  24.       mapSideCombine: Boolean = true,  
  25.       serializer: Serializer = null)(implicit ct: ClassTag[C]): RDD[(K, C)] = self.withScope {  
  26.     require(mergeCombiners != null, "mergeCombiners must be defined") // required as of Spark 0.9.0  
  27.     if (keyClass.isArray) {  
  28.       if (mapSideCombine) {  
  29.         throw new SparkException("Cannot use map-side combining with array keys.")  
  30.       }  
  31.       if (partitioner.isInstanceOf[HashPartitioner]) {  
  32.         throw new SparkException("HashPartitioner cannot partition array keys.")  
  33.       }  
  34.     }  
  35.     val aggregator = new Aggregator[K, V, C](  
  36.       self.context.clean(createCombiner),  
  37.       self.context.clean(mergeValue),  
  38.       self.context.clean(mergeCombiners))  
  39.     if (self.partitioner == Some(partitioner)) {  
  40.       self.mapPartitions(iter => {  
  41.         val context = TaskContext.get()  
  42.         new InterruptibleIterator(context, aggregator.combineValuesByKey(iter, context))  
  43.       }, preservesPartitioning = true)  
  44.     } else {  
  45.       new ShuffledRDD[K, V, C](self, partitioner)  
  46.         .setSerializer(serializer)  
  47.         .setAggregator(aggregator)  
  48.         .setMapSideCombine(mapSideCombine)  
  49.     }  
  50.   }  

通过查看combineByKeyWithClassTag的,发现reduceByKey默认在map端进行合并,那就是在shuffle前进行合并,如果合并了一些数据,那在shuffle时进行溢写则减少了磁盘IO,所以reduceByKey会快一些。

 

【Spark系列2】reduceByKey和groupByKey区别与用法 在spark中,我们知道一切的操作都是基于RDD的。在使用中,RDD有一种非常特殊也是非常实用的format——pair RDD,即RDD的每一行是(key, value)的格式。这种格式很像Python的字典类型,便于针对key进行一些处理。 针对pair RDD这样的特殊形式,spark中定义了许多方便的操作,今天主要介绍一下reduceByKey和groupByKey,因为在接下来 阅读详情

相关推荐

Spark学习笔记 --- ReduceByKey与GroupByKey的区别

一、功能对比: reduceByKey(func)的功能是,使用func函数合并具有相同键的值。 比如,reduceByKey((a,b) => a+b),有四个键值对(“spark”,1)、(“spark”,2)、(“hadoop”,3)和(“hadoop”,5) groupByKey()的功能是,对具有相同键的值进行分组。 比如,对四个键值对(“spark”,...

杨鑫newlife的专栏 1287

一文看懂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万+

PICO G2 4K Unity开发环境配置完全指南

VR开发中,Android平台的硬件适配与Unity版本兼容性是基础性技术命题。PICO G2 4K作为基于骁龙845+Android 8.1的专用VR一体机,其开发链路高度依赖特定Unity LTS版本(2020.3.41f1)、NDK r21e及OpenJDK 11等工具链组合,本质是嵌入式Android VR Runtime与Unity IL2CPP ABI的深度对齐问题。该配置方案不仅解决ADB识别、APK签名、Logcat捕获等工程痛点,更支撑手柄6DoF追踪、射线交互、Haptic反馈等核心XR

weixin_30298497的博客 622

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

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

weixin_42326851的博客 1993

代谢组+微生物组联合分析实战:从样本处理到生物标志物筛选的完整流程

本文详细介绍了代谢组与微生物组联合分析的全流程,从样本采集、处理到生物标志物筛选的科学实践。重点解析了样本类型匹配、共提取技术、质控协同监控及多维度关联分析方法,帮助研究者系统掌握这一前沿技术,为疾病机制研究和精准医疗提供新视角。

weixin_28335283的博客 220

人机交互期末复习笔记

人机交互期末复习笔记 进行复习的童鞋们可以跟着清华大学《人机交互基础教程第3版(孟祥旭、李学庆、杨承磊、王璐编著)的书籍参照借阅。上面的一字一句皆是敲键盘敲出来的,并且掌握课本的基本内容。 博客中的知识点有些地方会进行粗略的跳过(主要的大框架没有省略),建议有同样需求的读者结合书本与博客一同借阅。本博客有错误的地方多多指正,谢谢大家~ 文章目录人机交互期末复习笔记第一章 绪论 P11.1 人机交互的概念1.2 人机交互的研究内容1.3 人机交互的发展历史(只介绍人机交互阶段)第二章 感知和认知基础 P122

server643的博客 5027

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

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

newhandnew413的博客 1974

Multisim14.2新建项目教程

这里用一个案例,具体说明电路仿真分析的基本流程。等。本案例的电路目的:对一个交流小信号进行采样、放大,将交流小信号转换成脉冲信号。然后用一个简单的数字计数器对脉冲信号的周期进行计数,并用七段数码管和发光二极管显示计数过程。启动Multisim 14.2软件,在“工作区”出现一个名为“设计1”的空白图纸,选择“文件”→“另存为(a)…”,出现一个标准的Windows保存文件对话框。按导航定位到要保存文件的位置,输入“×××”作为文件名,然后单击“保存”按钮。注意。

Skiko的博客 4048

reduceByKey、groupByKey、aggregateByKey区别及用法

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

qq_39565127的博客 1692

在 ABAP 中把变量一次写对:深入理解 FINAL 内联声明与不可变变量

摘要:ABAP中的FINAL声明操作符用于定义不可变变量,强调"当前上下文中的唯一写位置",能有效防止变量被意外修改,提升代码健壮性和可读性。官方建议优先在单次赋值的场景使用FINAL替代DATA。其核心规则包括:1)写位置唯一但可多次执行(如循环内);2)不创建块级作用域;3)对引用变量仅约束引用本身而非对象内容。典型适用场景包括:结果值只读、输入快照保存和中间结果保护。例外情况如游标变量不适用,因需多次写操作。正确使用FINAL可显著降低代码维护风险。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1052

全国区块链职业技能大赛国赛考题前端功能开发

全国区块链职业技能大赛国赛考题区块链应用前端功能开发

本郡主是喵 1340

【转载】Spark中:reduceByKey和groupByKey区别与用法

reduceByKey和groupByKey的区别

明日韭菜 881

IMX6ULL---从零开始移植uboot-imx

IMX6ULL---从零开始移植uboot-imx

weixin_42162924的博客 1031

【spark】常用转换操作:reduceByKey和groupByKey

【spark】常用转换操作:reduceByKey和groupByKey

u011250186的博客 85

遗传算法(GA)全面解析:从生物基础到工程实践

本文全面解析了遗传算法(GA),从其生物基础到工程实践应用。遗传算法模拟自然进化过程,通过选择、交叉和变异等操作在解空间中高效搜索最优解。文章详细介绍了算法的生物学基础(达尔文进化论、孟德尔遗传定律)、基本概念(种群、个体、基因等)和核心思想。重点阐述了遗传算法的数学模型,包括编码机制、适应度函数设计、遗传算子(选择、交叉、变异)以及关键控制参数。最后提供了一个完整的Python实现示例,展示了遗传算法求解函数最大值问题的具体应用。该算法具有群体搜索、概率导向、无需梯度等特点,适用于各类复杂优化问题。

qq_42212808的博客 1189

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

Spark的RDD转换算子-key-value型-partitionBy、reduceByKey、groupByKey

Spark的RDD转换算子-key-value型-partitionBy、reduceByKey、groupByKey 一、partitionBy 函数签名 def partitionBy(partitioner: Partitioner): RDD[(K, V)] 将数据按照指定 Partitioner 重新进行分区。Spark 默认的分区器是 HashPartitioner val rdd: RDD[(Int, String)] = sc.makeRDD(Array((1,"aaa"),(2,"bb

weixin_46429290的博客 717

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

Spark中reduceByKey、groupByKey和combineByKey的区别

在spark中,reduceByKey、groupByKey和combineByKey这三种算子用的较多,其中:•reduceByKey用于对每个key对应的多个value进行merge操作,最重要的是它能够在本地先进行merge操作,并且merge操作可以通过函数自定义;•groupByKey也是对每个key进行操作,但只生成一个sequence,groupByKey本身不能自定义函数,需要先用...

Cody_hong的博客 9712

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

上一篇: Hive如何根据表中某个字段动态分区
下一篇: 遍历ArrayList,并删除某些元素的方法实现
baigp
博客等级 码龄14年 68粉丝 30原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值