Spark中有两个类似的api,分别是reduceByKey和groupByKey。这两个的功能类似,但底层实现却有些不同,那么为什么要这样设计呢?我们来从源码的角度分析一下。

先看两者的调用顺序(都是使用默认的Partitioner,即defaultPartitioner)

所用spark版本:spark2.1.0

先看reduceByKey

Step1

  def reduceByKey(func: (V, V) => V): RDD[(K, V)] = self.withScope {
reduceByKey(defaultPartitioner(self), func)
}

Setp2

  def reduceByKey(partitioner: Partitioner, func: (V, V) => V): RDD[(K, V)] = self.withScope {
combineByKeyWithClassTag[V]((v: V) => v, func, func, partitioner)
}

Setp3

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这个方法。这个方法有两个参数我们来重点看一下,

def combineByKeyWithClassTag[C](
createCombiner: V => C,
mergeValue: (C, V) => C,
mergeCombiners: (C, C) => C,
partitioner: Partitioner,
mapSideCombine: Boolean = true,
serializer: Serializer = null)

首先是partitioner参数,这个即是RDD的分区设置。除了默认的defaultPartitioner,Spark还提供了RangePartitioner和HashPartitioner外,此外用户也可以自定义partitioner。通过源码可以发现如果是HashPartitioner的话,那么是会抛出一个错误的。

然后是mapSideCombine参数,这个参数正是reduceByKey和groupByKey最大不同的地方,它决定是是否会先在节点上进行一次Combine操作,下面会有更具体的例子来介绍。

然后是groupByKey

Step1

  def groupByKey(): RDD[(K, Iterable[V])] = self.withScope {
groupByKey(defaultPartitioner(self))
}

Step2

  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])]]
}

Setp3

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)
}
}

结合上面reduceByKey的调用链,可以发现最终其实都是调用combineByKeyWithClassTag这个方法的,但调用的参数不同。

reduceByKey的调用

combineByKeyWithClassTag[V]((v: V) => v, func, func, partitioner)

groupByKey的调用

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

正是两者不同的调用方式导致了两个方法的差别,我们分别来看

  • reduceByKey的泛型参数直接是[V],而groupByKey的泛型参数是[CompactBuffer[V]]。这直接导致了reduceByKey和groupByKey的返回值不同,前者是RDD[(K, V)],而后者是RDD[(K, Iterable[V])]

  • 然后就是mapSideCombine=false了,这个mapSideCombine参数的默认是true的。这个值有什么用呢,上面也说了,这个参数的作用是控制要不要在map端进行初步合并(Combine)。可以看看下面具体的例子。


从功能上来说,可以发现ReduceByKey其实就是会在每个节点先进行一次合并的操作,而groupByKey没有。

这么来看ReduceByKey的性能会比groupByKey好很多,因为有些工作在节点已经处理了。那么groupByKey为什么存在,它的应用场景是什么呢?我也不清楚,如果观看这篇文章的读者知道的话不妨在评论里说出来吧。非常感谢!

spark RDD,reduceByKey vs groupByKey的更多相关文章

  1. spark RDD,DataFrame,DataSet 介绍

    弹性分布式数据集(Resilient Distributed Dataset,RDD) RDD是Spark一开始就提供的主要API,从根本上来说,一个RDD就是你的数据的一个不可变的分布式元素集合,在 ...

  2. Spark SQL,如何将 DataFrame 转为 json 格式

    今天主要介绍一下如何将 Spark dataframe 的数据转成 json 数据.用到的是 scala 提供的 json 处理的 api. 用过 Spark SQL 应该知道,Spark dataf ...

  3. 【Spark算子】:reduceByKey、groupByKey和combineByKey

    在spark中,reduceByKey.groupByKey和combineByKey这三种算子用的较多,结合使用过程中的体会简单总结: 我的代码实践:https://github.com/wwcom ...

  4. reduceByKey和groupByKey区别与用法

    在spark中,我们知道一切的操作都是基于RDD的.在使用中,RDD有一种非常特殊也是非常实用的format——pair RDD,即RDD的每一行是(key, value)的格式.这种格式很像Pyth ...

  5. Spark RDD/Core 编程 API入门系列 之rdd案例(map、filter、flatMap、groupByKey、reduceByKey、join、cogroupy等)(四)

    声明: 大数据中,最重要的算子操作是:join  !!! 典型的transformation和action val nums = sc.parallelize(1 to 10) //根据集合创建RDD ...

  6. Spark RDD/Core 编程 API入门系列之map、filter、textFile、cache、对Job输出结果进行升和降序、union、groupByKey、join、reduce、lookup(一)

    1.以本地模式实战map和filter 2.以集群模式实战textFile和cache 3.对Job输出结果进行升和降序 4.union 5.groupByKey 6.join 7.reduce 8. ...

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

    1.reduceByKey(func) 功能: 使用 func 函数合并具有相同键的值. 示例: val list = List("hadoop","spark" ...

  8. Spark 学习笔记之 distinct/groupByKey/reduceByKey

    distinct/groupByKey/reduceByKey: distinct: import org.apache.spark.SparkContext import org.apache.sp ...

  9. spark中的pair rdd,看这一篇就够了

    本文始发于个人公众号:TechFlow,原创不易,求个关注 今天是spark专题的第四篇文章,我们一起来看下Pair RDD. 定义 在之前的文章当中,我们已经熟悉了RDD的相关概念,也了解了RDD基 ...

随机推荐

  1. 全网最全的Windows下Anaconda2 / Anaconda3里正确下载安装爬虫框架Scrapy(离线方式和在线方式)(图文详解)

    不多说,直接上干货! 参考博客 全网最全的Windows下Anaconda2 / Anaconda3里正确下载安装OpenCV(离线方式和在线方式)(图文详解) 第一步:首先,提示升级下pip 第二步 ...

  2. SpringCloud入门之YAML格式文件规范学习

    1. 认识 YAML YAML(发音 /ˈjæməl/)是一个类似 XML.JSON 的数据序列化语言.其强调以数据为中心,旨在方便人类使用:并且适用于日常常见任务的现代编程语言.因而 YAML 本身 ...

  3. git 下载部分目录

    需求 github上整个工厂比较大,下起来费劲,如何只下载一个单独的文件件呢? 方法一 以:https://github.com/eugenp/tutorials为例,下载其中的 spring-kaf ...

  4. 浅谈JavaScript之事件(上)

    一  简述JavaScript及其在浏览器中的地位 (一)  浏览器主要构成 虽然不同浏览器之间存在差异(如Google Chrome,Firefox,Safari和IE等),但单从浏览器构成来说,大 ...

  5. Perl输出复杂数据结构:Data::Dumper,Data::Dump,Data::Printer

    输出复杂结构 Data::Dumper.Data::Dump.Data::Printer都可以用来输出复杂的数据结构.本文只介绍简单的几个输出形式,以后再需要的地方再详细介绍. 前两者建议传递数据结构 ...

  6. Perl正则表达式引用

    正则表达式两篇: 基础正则 Perl正则 本文是对Perl正则的一点扩展,主要内容是使用qr//创建正则对象,以及一些其它的技巧. qr//创建正则对象 因为可以在正则模式中使用变量替换,所以我们可以 ...

  7. Python with/as和contextlib上下文管理使用说明

    with/as 使用open打开过文件的对with/as都已经非常熟悉,其实with/as是对try/finally的一种替代方案. 当某个对象支持一种称为"环境管理协议"的协议时 ...

  8. JS_单个或多个文件上传_不支持单独修改

    A-From表单直接填写提交地址,不过干预: 1. 单文件上传 最简单的文件上传,是单文件上传,form标签中加入enctype="multipart/form-data",for ...

  9. C#语言中字段和属性相关知识剖析

    针对C#中的字段和属性,很多初学者无法区分这两者之间的区别. 字段与属性比较 字段;是一种“成员变量”,一般在类的内部做数据交互使用,占用内存空间. 属性:a.是一种逻辑变量,一般跟字段一起结合起来使 ...

  10. Winform下KeyDown,KeyPress,KeyUp事件的总结(转)

    原文: http://www.cnblogs.com/xiashengwang/archive/2011/09/15/2578798.html 在winform程序中,经常会用到这几个事件用于控制数字 ...