关于 Shuffle 概念及其算子 | 青训营笔记

118 阅读2分钟

这是我参与「第四届青训营 」笔记创作活动的第 8 天!

1、Shuffle 简述:


(1)关于 MapReduce

  • 2004 年谷歌发布了《MapReduce:Simplified Data Processing on large Clusters》论文。
  • 在开源实现的 MapReduce 中,存在 Map、Shuffle、Reduce 三个阶段。 image.png

(2)Map 阶段

  • Map 阶段,即在单机上进行的针对一小块数据的计算过程。 image.png

(3)Shuffle 阶段

  • Shuffle 阶段,即在 Map 阶段的基础上,进行数据移动,为后续的 Reduce 阶段做准备。 image.png

(4)Reduce 过程

  • Reduce 过程,即对移动后的数据进行处理,依旧是在单机上处理一小份数据。 image.png

(5)Shuffle 对性能的重要性显著的原因

image.png

  • M*R 次网络连接
  • 大量的数据移动
  • 数据丢失风险
  • 可能存在大量的排序操作
  • 大量的数据序列化、反序列化操作
  • 数据压缩

2、Shuffle 算子


(1)算子分类

  • 大致分为四类 image.png

(2)算子应用

val text = sc.textFile("mytextfile.txt")
val counts = text
    .flatMap(line => line.split("  "))
    .map(word => (word, 1))
    .reduceByKey(_+_)

(3)算子依赖

1.Spark 中对 Shuffle 的抽象 - 宽依赖、窄依赖

image.png

  • 窄依赖:父 RDD 的每个分片至多被子 RDD 中的每一个分片所依赖。
  • 宽依赖:父 RDD 的分片可能被子 RDD 中的多个分片所依赖。
2.算子内部的依赖关系(ShuffleDependency)
  • CoGroupRDD
    • Cogroup
      • fullOuterJoin、rightOuterJoin、leftOuterJoin
      • join
  • ShuffledRDD
    • combineByKeyWithClassTag
      • combineByKey
      • reduceByKey
    • Coalesce
    • sortByKey
      • sortBy
3.ShuffleDependency 构造
  • A single key-value pair RDD, i, e. RDD[Product2[K, V]]

  • Partitioner(available as partitioner property)

  • Serializer

  • Optional key ordering (of Scala's scala.math.Ordering type)

  • optional Aggregator

  • mapSideCombine flag which is disabled (i, e, false) by default

  • ShuffleDependency 构造 - partitioner

    • 两个接口
      • numberPartitions
      • getPartition
    • 经典实现
      • HashPartitoner
abstract class Partitioner extends Serializable{
    def numPartitions: Int
    def getPartition(key: Any): Int
}
class HashPartitioner(partitions: Int) extends Partitioner {
    require(partitions >= 0, s"Number of partitions ($partitions) cannot be Negative"
    
    def numPartitions: Int = partitions
    
    def getPartition(key: Any): Int = key match {
        case null => 0
        case _ => Utils.nonNegativeMod(key.hashCode, numPartitions)
    }
}
  • ShuffleDependency 构造 - Aggregator
    • createCombiner: 只有一个 value 的时候初始化的方法
    • mergeValue: 合并一个 value 到 Aggregator 中
    • mergeCombiners: 合并两个 Aggregator