`
bit1129
  • 浏览: 1073162 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

【Spark四十】RDD算子逻辑执行图第一部分

 
阅读更多

 

1.count

2.groupByKey

3.join

4.union

5.reduceByKey

 

Shuffle/Dependency总结

 

ShuffleMapTask将数据写到内存(或者磁盘)供ResultTask来拉取,那么写的策略是什么?ResultTask怎么知道拉取属于它的数据,那么这里头Mapper和Reducer应该通力协作,工作完成数据的写和读操作。

 

1. count

  /**
   * Return the number of elements in the RDD.
   */
  def count(): Long = sc.runJob(this, Utils.getIteratorSize _).sum

Utils.getIteratorSize算出一个worker上的elements的数目,然后然后通过sum操作,将所有worker节点上的elements数目进行相加

先在每个 partition 上执行 count,然后执行结果被发送到 driver,最后在 driver 端进行 sum。

 

2. groupByKey

 

package spark.examples

import java.util.Random

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.SparkContext._

/**
 * Usage: GroupByTest [numMappers] [numKVPairs] [valSize] [numReducers]
 */
object SparkGroupByTest {
  def main(args: Array[String]) {
    val sparkConf = new SparkConf().setAppName("GroupBy Test").setMaster("local ")
    val numMappers = 1//100
    val numKVPairs = 100//00
    val valSize = 10//00
    val numReducers = 36

    val sc = new SparkContext(sparkConf)

   ///定义numMappers个元素的集合,对每个元素调用flatMap操作
    val pairs1 = sc.parallelize(0 until numMappers, numMappers).flatMap { p =>

     ///随机数,作为arr1的元素类型(K,V)中的K
      val ranGen = new Random

     ///定义一个数组,长度为numKVPairs。元素类型是(K,V)的二元组,K的类型是Int,V的类型是字节数组(字节长度为valSize)
      val arr1 = new Array[(Int, Array[Byte])](numKVPairs)

     ///对长度为numKVPairs的arr1进行填充值
      for (i <- 0 until numKVPairs) {

        ///创建数组元素的字节数组,数组长度为valSize
        val byteArr = new Array[Byte](valSize)
        ranGen.nextBytes(byteArr)
        //K是随机生成的整数
        arr1(i) = (ranGen.nextInt(Int.MaxValue), byteArr)
      }
      arr1
    }.cache
    // Enforce that everything has been calculated and in cache

   //action操作,将数据缓存,并且返回所有的(K,V)对
    println(pairs1.toDebugString);
    /*cache的是FlatMappedRDD
    FlatMappedRDD[1] at flatMap at SparkGroupbyTest.scala:26 [Memory Deserialized 1x Replicated]
    ParallelCollectionRDD[0] at parallelize at SparkGroupbyTest.scala:26 [Memory Deserialized 1x Replicated]
     */

    pairs1.count

    ///根据Reducer个数做groupBy操作,
    println(pairs1.groupByKey(numReducers).count)

    sc.stop()
  }
}

 

 

1. groupByKey的含义是对(K,V)进行合并。

例如:

节点1: (1,2),(1,3),(2,6)

节点2: (1,7),(3,8),(2,9)

那么groupByKey结束后得到的结果是什么?

(1,(2,7)),(1,(3,7)),(2,(6,9)), (3,(_,8))? 不对,最后的结果,应该是Key是唯一的

 

2. 上面的例子中,reducer的个数是36,那么要做group操作,所以,来自各个worker节点的相同的Key必须由同一个reducer上来处理,这是怎么做到的?即reducer拉取数据时,是按照Key做Hash么?hash(key)%36. 即m个mapper结果,由r个reducer消费,如何消费?每个mapper都有reducer的数据,reducer如何拉取应该由它处理的这些数据?从不同的mapper中拉取数据,这就是Shuffle Write的工作!是分布式计算框架的核心之一

3. 如下图所示:ShuffledRDD存放的时比较合并的结果,只是从FlatMappRDD将原始数据拉取过来?拉取数据时,Mapp端没有做预combine操作??

4. groupByKey操作是一个根据Key把所有的Value聚合到一起的操作,这跟SQL的groupBy操作不一样,SQL的groupBy操作的结果是,一组的结果是每个占据一行。

5. groupByKey不要是用map端的combine

 

 /**
   * 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.
   */
  //groupByKey不使用map端的combine,为什么还要创建combineByKey?额。。指明了mapSideCombine=false
  def groupByKey(partitioner: Partitioner): RDD[(K, Iterable[V])] = {
    // 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 = combineByKey[CompactBuffer[V]](
      createCombiner, mergeValue, mergeCombiners, partitioner, mapSideCombine=false)
    bufs.asInstanceOf[RDD[(K, Iterable[V])]]
  }
 

 

 

 

 

 

 

 

3. join

 

package spark.examples

import org.apache.spark.{SparkContext, SparkConf}
import org.apache.spark.SparkContext._

object SparkRDDJoin {

  def main(args : Array[String]) {
    val conf = new SparkConf().setAppName("Join").setMaster("local");
    val sc = new SparkContext(conf);

    //第一个参数是集合,第二个参数是分区数
    val rdd1 = sc.parallelize(List((1,2),(2,3), (3,4),(4,5),(5,6)), 3)
    val rdd2 = sc.parallelize(List((3,6),(2,8)), 2);

     //join操作的RDD的元素类型必须是K/V类型
    val pairs = rdd1.join(rdd2);

    println(pairs.foreach(println(_)));

   /*
   (3) FlatMappedValuesRDD[4] at join at SparkRDDJoin.scala:17 []
 |  MappedValuesRDD[3] at join at SparkRDDJoin.scala:17 []
 |  CoGroupedRDD[2] at join at SparkRDDJoin.scala:17 []
 +-(3) ParallelCollectionRDD[0] at parallelize at SparkRDDJoin.scala:13 []
 +-(2) ParallelCollectionRDD[1] at parallelize at SparkRDDJoin.scala:14 []
   */
   println(pairs.toDebugString)
  }

}

 

4. Union

源代码:

 

package spark.examples

import org.apache.spark.{SparkContext, SparkConf}
import org.apache.spark.SparkContext._

object SparkRDDUnion {

  def main(args : Array[String]) {
    val conf = new SparkConf().setAppName("Join").setMaster("local");
    val sc = new SparkContext(conf);

    //第一个参数是集合,第二个参数是分区数
    val rdd1 = sc.parallelize(List((1,2),(2,3), (3,4),(4,5),(5,6)), 3)
    val rdd2 = sc.parallelize(List((3,6),(2,8)), 2);

    val pairs = rdd1.union(rdd2);
    
    pairs.saveAsTextFile("file:///D:/union" + System.currentTimeMillis());

    println(pairs.toDebugString)
  }

}

 

1. RDD依赖图

 UnionRDD[2] at union at SparkRDDUnion.scala:16 []
 |  ParallelCollectionRDD[0] at parallelize at SparkRDDUnion.scala:13 []
 |  ParallelCollectionRDD[1] at parallelize at SparkRDDUnion.scala:14 []

2. 没有Shuffle过程,因为执行过程中没有执行ShuffleMapTask,而是仅仅执行了ResultTask(一共有五个任务)

3. 结果有5个结果文件,part-00000到part-00004,内容分布为

part-00000:(1,2)

part-00001:(2,3) (3,4)

part-00002:(4,5) (5,6)

part-00003: (3,6)

part-00004:(2,8)

问题:结果的规律在哪里?

4. RDD的依赖图

 

 

5. reduceByKey

1.源代码

2.RDD依赖图

object SparkWordCount {
  def main(args: Array[String]) {
    System.setProperty("hadoop.home.dir", "E:\\devsoftware\\hadoop-2.5.2\\hadoop-2.5.2");
    val conf = new SparkConf()
    conf.setAppName("SparkWordCount")
    conf.setMaster("local[3]")
    conf.set("spark.shuffle.manager", "sort");
    val sc = new SparkContext(conf)
    val rdd1 = sc.textFile("file:///D:/word.in.3");
    val rdd2 = rdd1.flatMap(_.split(" "))
    val rdd3 = rdd2.map((_, 1))
    val rdd4 = rdd3.reduceByKey(_ + _); ///关键看预reduce是在第一个stage的哪个RDD中执行的
    println("rdd3:" + rdd3.toDebugString)
    rdd3.saveAsTextFile("file:///D:/wordout" + System.currentTimeMillis());
    sc.stop
  }
}

 

3.RDD的reduceByKey会在mapper端做mini reduce,即进行数据的预reduce,在map端对重复Key进行func操作

4. reduceByKey使用了mapper端的combine,那么,它是在调用RDD的reduceByKey的时候,由于隐式类型转换,而调用

 

combineKey的三个函数参数含义解释:

假设一组具有相同 K 的 <K, V> records 正在一个个流向 combineByKey(),createCombiner 将第一个 record 的 value 初始化为 c (比如,c = value),然后从第二个 record 开始,来一个 record 就使用 mergeValue(c, record.value) 来更新 c,比如想要对这些 records 的所有 values 做 sum,那么使用 c = c + record.value。等到 records 全部被 mergeValue(),得到结果 c。假设还有一组 records(key 与前面那组的 key 均相同)一个个到来,combineByKey() 使用前面的方法不断计算得到 c'。现在如果要求这两组 records 总的 combineByKey() 后的结果,那么可以使用 final c = mergeCombiners(c, c') 来计算。

 

 

 

 /**
   * 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
   * Note that 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]). 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).
   */
  def combineByKey[C](createCombiner: V => C,
      mergeValue: (C, V) => C,
      mergeCombiners: (C, C) => C,
      partitioner: Partitioner,
      mapSideCombine: Boolean = true,
      serializer: Serializer = null): RDD[(K, C)] = {
    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("Default partitioner cannot partition array keys.")
      }
    }
    val aggregator = new Aggregator[K, V, C](createCombiner, mergeValue, mergeCombiners) ///Aggragator的构造是三个函数
    if (self.partitioner == Some(partitioner)) { ////这是什么意思?无需生成ShuffledRDD,但还是做了combineValuesByKey操作
      self.mapPartitions(iter => {
        val context = TaskContext.get()
        new InterruptibleIterator(context, aggregator.combineValuesByKey(iter, context))
      }, preservesPartitioning = true)
    } else { ///得到ShuffleRDD,携带aggregator以及mapSieCombine
      new ShuffledRDD[K, V, C](self, partitioner)
        .setSerializer(serializer)
        .setAggregator(aggregator)
        .setMapSideCombine(mapSideCombine)
    }
  }

 

 

 

 

 

 

RDD算子与shuffleDependency小结

 

combineByKey()

分析了这么多 RDD 的逻辑执行图,它们之间有没有共同之处?如果有,是怎么被设计和实现的?

仔细分析 RDD 的逻辑执行图会发现,ShuffleDependency 左边的 RDD 中的 record 要求是 <key, value> 型的,经过 ShuffleDependency 后,包含相同 key 的 records 会被 aggregate 到一起,然后在 aggregated 的 records 上执行不同的计算逻辑。实际执行时很多 transformation() 如 groupByKey(),reduceByKey() 是边 aggregate 数据边执行计算逻辑的,因此共同之处就是 aggregate 同时 compute()。Spark 使用 combineByKey() 来实现这个 aggregate + compute() 的基础操作。

combineByKey() 的定义如下:

 

  /**
   * 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
   * Note that 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]). 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).
   */
  def combineByKey[C](createCombiner: V => C,
      mergeValue: (C, V) => C,
      mergeCombiners: (C, C) => C,
      partitioner: Partitioner,
      mapSideCombine: Boolean = true,
      serializer: Serializer = null): RDD[(K, C)] = {
    require(mergeCombiners != null, "mergeCombiners must be defined") // required as of Spark 0.9.0
    if (keyClass.isArray) {///如果Key是数组,那么既不能做map端的combine,也不能使用Hash分区器
      if (mapSideCombine) { 
        throw new SparkException("Cannot use map-side combining with array keys.")
      }
      if (partitioner.isInstanceOf[HashPartitioner]) {
        throw new SparkException("Default partitioner cannot partition array keys.")
      }
    }
    ////通过createCombiner, mergeValue, mergeCombiners三元组构造Aggregator
    val aggregator = new Aggregator[K, V, C](createCombiner, mergeValue, mergeCombiners)
   
    if (self.partitioner == Some(partitioner)) { ///
      self.mapPartitions(iter => { ///转换为MapPartitionsRDD,这是窄依赖
        val context = TaskContext.get()
        new InterruptibleIterator(context, aggregator.combineValuesByKey(iter, context))
      }, preservesPartitioning = true)
    } else {///构造ShuffleRDD时,需要带入Aggregator 
      new ShuffledRDD[K, V, C](self, partitioner)
        .setSerializer(serializer)
        .setAggregator(aggregator)
        .setMapSideCombine(mapSideCombine)
    }
  }

 

 

 

其中主要有三个参数 createCombiner,mergeValue 和 mergeCombiners。简单解释下这三个函数及 combineByKey() 的意义,注意它们的类型:

假设一组具有相同 K 的 <K, V> records 正在一个个流向 combineByKey(),createCombiner 将第一个 record 的 value 初始化为 c (比如,c = value),然后从第二个 record 开始,来一个 record 就使用 mergeValue(c, record.value) 来更新 c,比如想要对这些 records 的所有 values 做 sum,那么使用 c = c + record.value。等到 records 全部被 mergeValue(),得到结果 c。假设还有一组 records(key 与前面那组的 key 均相同)一个个到来,combineByKey() 使用前面的方法不断计算得到 c'。现在如果要求这两组 records 总的 combineByKey() 后的结果,那么可以使用 final c = mergeCombiners(c, c') 来计算。

 

 代码中有段关键的逻辑,如下所示,含义是如果条件成立,则返回MappedPartitionRDD,这是一个窄依赖,否则就是ShuffledRDD(宽依赖)

 

    if (self.partitioner == Some(partitioner)) {
      self.mapPartitions(iter => {
        val context = TaskContext.get()
        new InterruptibleIterator(context, aggregator.combineValuesByKey(iter, context))
      }, preservesPartitioning = true)
    }

 self.partitioner表示的父RDD的partitioner,而Some(partitioner)的partitioner表示的combineByKey传入的参数,问题这个partitioner是如何传入的?

 

 对于reduceByKey而言,

 /**
   * Merge the values for each key using an associative 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)] = {
    reduceByKey(new HashPartitioner(numPartitions), func) ////使用HashPartitioner
  }

  /**
   * Merge the values for each key using an associative 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)] = {
    reduceByKey(defaultPartitioner(self), func) ////也是使用HashPartitioner
  }

 

 defaultPartitioner的代码:

/**
   * Choose a partitioner to use for a cogroup-like operation between a number of RDDs.
   *
   * If any of the RDDs already has a partitioner, choose that one.
   *
   * Otherwise, we use a default HashPartitioner. For the number of partitions, if
   * spark.default.parallelism is set, then we'll use the value from SparkContext
   * defaultParallelism, otherwise we'll use the max number of upstream partitions.
   *
   * Unless spark.default.parallelism is set, the number of partitions will be the
   * same as the number of partitions in the largest upstream RDD, as this should
   * be least likely to cause out-of-memory errors.
   *
   * We use two method parameters (rdd, others) to enforce callers passing at least 1 RDD.
   */
  def defaultPartitioner(rdd: RDD[_], others: RDD[_]*): Partitioner = {
    val bySize = (Seq(rdd) ++ others).sortBy(_.partitions.size).reverse
    for (r <- bySize if r.partitioner.isDefined) {
      return r.partitioner.get
    }
    if (rdd.context.conf.contains("spark.default.parallelism")) {
      new HashPartitioner(rdd.context.defaultParallelism)
    } else {
      new HashPartitioner(bySize.head.partitions.size)
    }
  }
}

 

 

 

  • 大小: 184.9 KB
  • 大小: 33.7 KB
  • 大小: 74 KB
分享到:
评论

相关推荐

    Spark1.4.1 RDD算子详解

    结合代码详细描述RDD算子的执行流程,并配上执行流程图

    Spark常用的算子以及Scala函数总结.pdf

    Transformation 算子用于对 RDD 进行变换操作,例如 map、filter 等,这些操作是延迟计算的,只有在触发 Action 算子时才真正执行。Action 算子会触发 SparkContext 提交作业并返回结果给驱动程序或写入外部存储系统...

    25个经典Spark算子的JAVA实现

    根据给定文件的信息,本文将详细介绍25个经典Spark算子的Java实现,并结合详细的注释及JUnit测试结果,帮助读者更好地理解Spark算子的工作原理及其应用方式。 ### Spark算子简介 在Apache Spark框架中,算子是用于...

    spark基本算子操作

    - **示例**:若`rdd1 = sc.parallelize([1, 2, 3])`,`rdd2 = sc.parallelize([3, 4, 5])`,执行`rdd1.union(rdd2)`后,得到的新RDD为`[1, 2, 3, 3, 4, 5]`。 8. **`intersection(otherDataset)`** - **功能**:...

    【SparkCore篇03】RDD行动算子1

    `first`算子返回RDD中的第一个元素。这在需要快速获取数据集的代表值时非常方便。 5. `take`算子: `take`算子返回RDD中的前n个元素组成的数组。这对于获取数据样本或者有限的输出很有帮助。 6. `takeOrdered`...

    【SparkCore篇02】RDD转换算子1

    SparkCore篇02主要介绍了RDD的一些基础转换算子,这些算子是Spark处理数据的核心工具。以下是关于这些算子的详细说明: 1. **map()**:map算子用于对RDD(Resilient Distributed Dataset)中的每个元素进行操作。它...

    Spark算子.pdf

    Spark对于大数据行业的实时处理数据来说,有着举足轻重的位置,特此学习整理了RDD 算子的各个含义,希望各位读者能够喜欢。谢谢

    sparkRDD函数大全

    spark rdd函数大全。spark rdd操作为core操作,虽然后续版本主要以dataset来操作,但是rdd操作也是不可忽略的一部分。

    spark算子基础讲义1

    Spark 算子是 Spark 框架中的一种数据处理单元,它可以将数据从一个RDD(Resilient Distributed Dataset)转换为另一个RDD。Spark 算子可以分为两大类: narrow dependency 算子和 wide dependency 算子。Narrow ...

    大数据spark学习之rdd概述

    RDD(Resilient Distributed Dataset)叫做弹性分布式数据集,是Spark中最基本的数据抽象,它代表一个不可变、可分区、里面的元素可并行计算的集合。在 Spark 中,对数据的所有操作不外乎创建 RDD、转化已有RDD 以及...

    Spark算子实例maven版

    1. **map()**: 这个算子用于将每个输入元素应用一个函数,然后返回一个新的RDD(弹性分布式数据集)。这是最基本的转换操作,可以用于对数据进行简单的处理,如数据清洗、计算等。 2. **filter()**: 通过传入一个...

    大数据实验报告Windows环境下安装Spark及RDD编程和Spark编程实现wordcount.doc

    大数据实验报告 Windows 环境下安装 Spark 及 RDD 编程和 Spark 编程实现 wordcount 本实验报告主要介绍了在 Windows 环境下安装 Spark 及 RDD 编程和 Spark 编程实现 wordcount 的步骤和过程。实验中首先安装了 ...

    spark RDD操作详解

    如果某一部分数据丢失,Spark可以根据这些依赖关系重新计算丢失的数据部分,而无需重新计算整个数据集。 - **高效性**:RDD的设计使得它可以高效地执行复杂的并行操作。 - **无需物化**:RDD的操作通常是在惰性求值...

    Spark算子的详细使用方法

    first 算子返回 RDD 中的第一个元素。take 算子返回 RDD 中的前 n 个元素。 在 Spark 编程中,我们可以使用 Transformation 算子来处理数据,然后使用 Action 算子来触发作业提交。例如,我们可以使用 map 算子将...

    Spark Transformation和Action算子速查表.pdf

    在Spark中,数据通常以RDD(弹性分布式数据集)的形式存在,并通过两种类型的算子进行处理:Transformation(转换)算子和Action(行动)算子。 **Transformation算子**:这些算子用于创建一个新的RDD。它们的操作...

    Spark思维导图之Spark RDD.png

    Spark思维导图之Spark RDD.png

    SparkTransformation和Action算子速查表.zip

    Transformation算子是延迟执行的,它们不立即执行任何操作,而是创建一个新的DAG(有向无环图)来表示数据流。这些算子主要包括: 1. **map()**:对数据集中的每个元素应用一个函数,生成新的数据集。 2. **flatMap...

    Spark学习--RDD编码

    当Spark对数据操作和转换时,会自动将RDD中的数据分发到集群,并将操作并行化执行。 Spark中的RDD是一个不可变的分布式对象集合。每个RDD都倍分为多个分区,这些分区运行在集群中的不同节点。RDD可以包含Python、...

    spark算子.docx

    flatMap 算子是 Spark 中另一个常用的 Transformations 算子,它可以将输入的数据按照用户提供的函数进行转换,并将结果展平成一个新的 RDD。flatMap 算子可以将一个 RDD 转换为另一个 RDD,每个输入元素都会被应用...

    spark RDD 论文 中文版

    Spark RDD(Resilient Distributed Datasets)作为Apache Spark的核心组件之一,在大数据处理领域扮演着至关重要的角色。本论文旨在探讨Spark RDD的设计理念及其在大数据处理中的优势,并通过具体的案例来证明其有效性...

Global site tag (gtag.js) - Google Analytics