前面一篇文章提到大数据开发-Spark Join原理详解,本文从源码角度来看cogroup 的join实现

1.分析下面的代码

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}
object JoinDemo {
def main(args: Array[String]): Unit = {
val conf = new SparkConf().setAppName(this.getClass.getCanonicalName.init).setMaster("local[*]")
val sc = new SparkContext(conf)
sc.setLogLevel("WARN") val random = scala.util.Random
val col1 = Range(1, 50).map(idx => (random.nextInt(10), s"user$idx"))
val col2 = Array((0, "BJ"), (1, "SH"), (2, "GZ"), (3, "SZ"), (4, "TJ"), (5, "CQ"), (6, "HZ"), (7, "NJ"), (8, "WH"), (0, "CD"))
val rdd1: RDD[(Int, String)] = sc.makeRDD(col1)
val rdd2: RDD[(Int, String)] = sc.makeRDD(col2)
val rdd3: RDD[(Int, (String, String))] = rdd1.join(rdd2)
println(rdd3.dependencies)
val rdd4: RDD[(Int, (String, String))] = rdd1.partitionBy(new HashPartitioner(3)).join(rdd2.partitionBy(new HashPartitioner(3)))
println(rdd4.dependencies)
sc.stop()
}
}

分析上面一段代码,打印结果是什么,这种join是宽依赖还是窄依赖,为什么是这样

2.从spark的ui界面来查看运行情况

关于stage划分和宽依赖窄依赖的关系,从2.1.3 如何区别宽依赖和窄依赖就知道stage与宽依赖对应,所以从rdd3和rdd4的stage的依赖图就可以区别宽依赖,可以看到join划分除了新的stage,所以rdd3的生成事宽依赖,另外rdd1.partitionBy(new HashPartitioner(3)).join(rdd2.partitionBy(new HashPartitioner(3))) 是另外的依赖图,所以可以看到partitionBy以后再没有划分新的 stage,所以是窄依赖。

3.join的源码实现

前面知道结论,是从ui图里面看到的,现在看join源码是如何实现的(基于spark2.4.5)

先进去入口方法,其中withScope的做法可以理解为装饰器,为了在sparkUI中能展示更多的信息。所以把所有创建的RDD的方法都包裹起来,同时用RDDOperationScope 记录 RDD 的操作历史和关联,就能达成目标。

  /**
* Return an RDD containing all pairs of elements with matching keys in `this` and `other`. Each
* pair of elements will be returned as a (k, (v1, v2)) tuple, where (k, v1) is in `this` and
* (k, v2) is in `other`. Performs a hash join across the cluster.
*/
def join[W](other: RDD[(K, W)]): RDD[(K, (V, W))] = self.withScope {
join(other, defaultPartitioner(self, other))
}

下面来看defaultPartitioner 的实现,其目的就是在默认值和分区器之间取一个较大的,返回分区器

def defaultPartitioner(rdd: RDD[_], others: RDD[_]*): Partitioner = {
val rdds = (Seq(rdd) ++ others)
// 判断有没有设置分区器partitioner
val hasPartitioner = rdds.filter(_.partitioner.exists(_.numPartitions > 0)) //如果设置了partitioner,则取设置partitioner的最大分区数
val hasMaxPartitioner: Option[RDD[_]] = if (hasPartitioner.nonEmpty) {
Some(hasPartitioner.maxBy(_.partitions.length))
} else {
None
} //判断是否设置了spark.default.parallelism,如果设置了则取spark.default.parallelism
val defaultNumPartitions = if (rdd.context.conf.contains("spark.default.parallelism")) {
rdd.context.defaultParallelism
} else {
rdds.map(_.partitions.length).max
} // If the existing max partitioner is an eligible one, or its partitions number is larger
// than the default number of partitions, use the existing partitioner.
//主要判断传入rdd是否设置了默认的partitioner 以及设置的partitioner是否合法
//或者设置的partitioner分区数大于默认的分区数
//条件成立则取传入rdd最大的分区数,否则取默认的分区数
if (hasMaxPartitioner.nonEmpty && (isEligiblePartitioner(hasMaxPartitioner.get, rdds) ||
defaultNumPartitions < hasMaxPartitioner.get.getNumPartitions)) {
hasMaxPartitioner.get.partitioner.get
} else {
new HashPartitioner(defaultNumPartitions)
}
} private def isEligiblePartitioner(
hasMaxPartitioner: RDD[_],
rdds: Seq[RDD[_]]): Boolean = {
val maxPartitions = rdds.map(_.partitions.length).max
log10(maxPartitions) - log10(hasMaxPartitioner.getNumPartitions) < 1
}
}

再进入join的重载方法,里面有个new CoGroupedRDD[K](Seq(self, other), partitioner)

def join[W](other: RDD[(K, W)], partitioner: Partitioner): RDD[(K, (V, W))] = self.withScope {
this.cogroup(other, partitioner).flatMapValues( pair =>
for (v <- pair._1.iterator; w <- pair._2.iterator) yield (v, w)
)
}
def cogroup[W](other: RDD[(K, W)], partitioner: Partitioner)
: RDD[(K, (Iterable[V], Iterable[W]))] = self.withScope {
if (partitioner.isInstanceOf[HashPartitioner] && keyClass.isArray) {
throw new SparkException("HashPartitioner cannot partition array keys.")
}
//partitioner 通过对比得到的默认分区器,主要是分区器中的分区数
val cg = new CoGroupedRDD[K](Seq(self, other), partitioner)
cg.mapValues { case Array(vs, w1s) =>
(vs.asInstanceOf[Iterable[V]], w1s.asInstanceOf[Iterable[W]])
}
} /**
* Return an RDD containing all pairs of elements with matching keys in `this` and `other`. Each
* pair of elements will be returned as a (k, (v1, v2)) tuple, where (k, v1) is in `this` and
* (k, v2) is in `other`. Performs a hash join across the cluster.
*/
def join[W](other: RDD[(K, W)], numPartitions: Int): RDD[(K, (V, W))] = self.withScope {
join(other, new HashPartitioner(numPartitions))
}

最后来看CoGroupedRDD,这是决定是宽依赖还是窄依赖的地方,可以看到如果左边rdd的分区和上面选择给定的分区器一致,则认为是窄依赖,否则是宽依赖

  override def getDependencies: Seq[Dependency[_]] = {
rdds.map { rdd: RDD[_] =>
if (rdd.partitioner == Some(part)) {
logDebug("Adding one-to-one dependency with " + rdd)
new OneToOneDependency(rdd)
} else {
logDebug("Adding shuffle dependency with " + rdd)
new ShuffleDependency[K, Any, CoGroupCombiner](
rdd.asInstanceOf[RDD[_ <: Product2[K, _]]], part, serializer)
}
}
}

总结,join时候可以指定分区数,如果join操作左右的rdd的分区方式和分区数一致则不会产生shuffle,否则就会shuffle,而是宽依赖,分区方式和分区数的体现就是分区器。

吴邪,小三爷,混迹于后台,大数据,人工智能领域的小菜鸟。

更多请关注

大数据开发-从cogroup的实现来看join是宽依赖还是窄依赖的更多相关文章

  1. 大数据开发实战:HDFS和MapReduce优缺点分析

    一. HDFS和MapReduce优缺点 1.HDFS的优势 HDFS的英文全称是 Hadoop Distributed File System,即Hadoop分布式文件系统,它是Hadoop的核心子 ...

  2. 大数据开发-Spark-拷问灵魂的5个问题

    1.Spark计算依赖内存,如果目前只有10g内存,但是需要将500G的文件排序并输出,需要如何操作? ①.把磁盘上的500G数据分割为100块(chunks),每份5GB.(注意,要留一些系统空间! ...

  3. 大数据开发-Flink-数据流DataStream和DataSet

    Flink主要用来处理数据流,所以从抽象上来看就是对数据流的处理,正如前面大数据开发-Flink-体系结构 && 运行架构提到写Flink程序实际上就是在写DataSource.Tra ...

  4. 2019春招——Vivo大数据开发工程师面经

    Vvio总共就一轮技术面+一轮HR面,技术面总体而言,比较宽泛,比较看中基础,面试的全程没有涉及简历上的东西(都准备好跟他扯项目了,感觉是抽取的题库...)具体内容如下: 1.熟悉Hadoop哪些组件 ...

  5. 杭州某知名xxxx公司急招大量java以及大数据开发工程师

    因公司战略以及业务拓展,收大量java攻城狮以及大数据开发攻城狮. 职位信息: java攻城狮: https://job.cnblogs.com/offer/56032 大数据开发攻城狮: https ...

  6. 大数据开发实战:Stream SQL实时开发三

    4.聚合操作 4.1.group by 操作 group by操作是实际业务场景(如实时报表.实时大屏等)中使用最为频繁的操作.通常实时聚合的主要源头数据流不会包含丰富的上下文信息,而是经常需要实时关 ...

  7. 大数据开发实战:Stream SQL实时开发二

    1.介绍 本节主要利用Stream SQL进行实时开发实战,回顾Beam的API和Hadoop MapReduce的API,会发现Google将实际业务对数据的各种操作进行了抽象,多变的数据需求抽象为 ...

  8. 大数据开发实战:Stream SQL实时开发一

    1.流计算SQL原理和架构 流计算SQL通常是一个类SQL的声明式语言,主要用于对流式数据(Streams)的持续性查询,目的是在常见流计算平台和框架(如Storm.Spark Streaming.F ...

  9. 大数据开发实战:Spark Streaming流计算开发

    1.背景介绍 Storm以及离线数据平台的MapReduce和Hive构成了Hadoop生态对实时和离线数据处理的一套完整处理解决方案.除了此套解决方案之外,还有一种非常流行的而且完整的离线和 实时数 ...

随机推荐

  1. CTFshow萌新赛-密码学签到

    查看密码信息 猜测为base家族 存在"^"符号,所以应该是在base64以上 使用base85解密 成功拿到flag

  2. 【译】Async/Await(三)——Aysnc/Await模式

    原文标题:Async/Await 原文链接:https://os.phil-opp.com/async-await/#multitasking 公众号: Rust 碎碎念 翻译 by: Praying ...

  3. 缓存淘汰算法 LRU 和 LFU

    LRU (Least Recently Used), 即最近最少使用用算法,是一种常见的 Cache 页面置换算法,有利于提高 Cache 命中率. LRU 的算法思想:对于每个页面,记录该页面自上一 ...

  4. CMU数据库(15-445)Lab1-BufferPoolManager

    0. 关于环境搭建请看 https://www.cnblogs.com/JayL-zxl/p/14307260.html 1. Task1 LRU REPLACEMENT POLICY 0. 任务描述 ...

  5. springmvc 字符串转日期格式

    http://www.mamicode.com/info-detail-2485490.html

  6. 24V转5V芯片,高输入电压LDO线性稳压器

    PW6206系列是一个高精度,高输入电压低静态电流,高速,低功耗降线性稳压器具有高纹波抑制.输入电压高达40V,负载电流为在VOUT=5V和VIN=7V时高达300mA.该设备采用BCD工艺制造.PW ...

  7. JAVA中@Override的含义

    @Override是伪代码,表示重写(当然不写也可以),不过写上有如下好处: 1.可以当注释用,方便阅读: 2.编译器可以给你验证@Override下面的方法名是否是你父类中所有的,如果没有则报错.例 ...

  8. uni-app开发经验分享十三:实现手机扫描二维码并跳转全过程

    最近使用 uni-app 开发 app ,需要实现一个调起手机摄像头扫描二维码功能,官网API文档给出了这样一个demo: // 允许从相机和相册扫码 uni.scanCode({ success: ...

  9. uni-app开发经验分享九: 组件传值

    一.父组件向子组件传值 通过props来实现,子组件通过props来接收父组件传过来的值! 1.逻辑梳理 父组件中: 第一步:引入子组件: import sonShow from '../../com ...

  10. uni-app 开发随笔(踩坑记录)

    这里总结一些uni-app开发时我遇到的坑 uni-app获取元素高度及屏幕高度(uni-app不可使用document) uni.getSystemInfo({ success: function( ...