Spark的RDD中key-value类型RDD处理函数reduceByKey,aggregateByKey,foldBykey和combineByKey理解

reduceByKey:
让相同的key进行分区内聚合,让相同key分区间聚合,这里涉及到了分区内预聚合,所以与groupByKey区别在于,groupByKey中shuffle过程数据量不会操作,shuffle落盘文件,相同操作reduceByKey的性能要优于groupByKey

def reduceByKey(func: (V, V) => V): RDD[(K, V)] = self.withScope {
    reduceByKey(defaultPartitioner(self), func)
  }
 /**
   * Merge the values for each key using an associative and commutative reduce function. This will
   * also perform the merging locally on each mapper before sending results to a reducer, similarly
   * to a "combiner" in MapReduce.
   */
  def reduceByKey(partitioner: Partitioner, func: (V, V) => V): RDD[(K, V)] = self.withScope {
    combineByKeyWithClassTag[V]((v: V) => v, func, func, partitioner) //分区内和分区间进行同样的计算
  }

aggregateByKey:
每个分区内key的第一个value与初始值ZoreVaue进行分区内计算
分区内进行计算
分区间进行计算
分区内计算规则与分区间计算不同

/**
  * Aggregate the values of each key, using given combine functions and a neutral "zero value".
  * This function can return a different result type, U, than the type of the values in this RDD,
  * V. Thus, we need one operation for merging a V into a U and one operation for merging two U's,
  * as in scala.TraversableOnce. The former operation is used for merging values within a
  * partition, and the latter is used for merging values between partitions. To avoid memory
  * allocation, both of these functions are allowed to modify and return their first argument
  * instead of creating a new U.
  */
 def aggregateByKey[U: ClassTag](zeroValue: U, partitioner: Partitioner)(seqOp: (U, V) => U,
     combOp: (U, U) => U): RDD[(K, U)] = self.withScope {
   // Serialize the zero value to a byte array so that we can get a new clone of it on each key
   val zeroBuffer = SparkEnv.get.serializer.newInstance().serialize(zeroValue)
   val zeroArray = new Array[Byte](zeroBuffer.limit)
   zeroBuffer.get(zeroArray)

   lazy val cachedSerializer = SparkEnv.get.serializer.newInstance()
   val createZero = () => cachedSerializer.deserialize[U](ByteBuffer.wrap(zeroArray))

   // We will clean the combiner closure later in `combineByKey`
   val cleanedSeqOp = self.context.clean(seqOp)
   combineByKeyWithClassTag[U]((v: V) => cleanedSeqOp(createZero(), v), //分区内第一个参数与zorevalue计算分区内计算
     cleanedSeqOp, combOp, partitioner) //
 }

foldBykey:
与aggregateByKey类似,只不过foldBykey分区内和分区间的计算规则是一样的

def foldByKey(
      zeroValue: V,
      partitioner: Partitioner)(func: (V, V) => V): RDD[(K, V)] = self.withScope {
    // Serialize the zero value to a byte array so that we can get a new clone of it on each key
    val zeroBuffer = SparkEnv.get.serializer.newInstance().serialize(zeroValue)
    val zeroArray = new Array[Byte](zeroBuffer.limit)
    zeroBuffer.get(zeroArray)

    // When deserializing, use a lazy val to create just one instance of the serializer per task
    lazy val cachedSerializer = SparkEnv.get.serializer.newInstance()
    val createZero = () => cachedSerializer.deserialize[V](ByteBuffer.wrap(zeroArray))

    val cleanedFunc = self.context.clean(func)
    combineByKeyWithClassTag[V]((v: V) => cleanedFunc(createZero(), v),
      cleanedFunc, cleanedFunc, partitioner)  //分区内和分区间计算规则一致
  }

combineByKey:
combineByKey共有三个参数:
第一个参数表示,把每个分区内的每个key的第一个value进行转化结构
第二个参数表示,每个分区内第一个参数进行 转化后与分区内第二参数进行的计算规则
第三个参数表示,分区间数据的计算规则

 /**
   * Simplified version of combineByKeyWithClassTag that hash-partitions the resulting RDD using the
   * existing partitioner/parallelism level. This method is here for backward compatibility. It
   * does not provide combiner classtag information to the shuffle.
   *
   * @see `combineByKeyWithClassTag`
   */
  def combineByKey[C](
      createCombiner: V => C,//分区内第一个value结构转化
      mergeValue: (C, V) => C,//分区内计算
      mergeCombiners: (C, C) => C): RDD[(K, C)] = self.withScope {
    combineByKeyWithClassTag(createCombiner, mergeValue, mergeCombiners)(null)
  }

从上面可知,上面的key-value类型函数底层都是通过调用combineByKeyWithClassTag 来实现,只不过分区内和分区间的计算规则不同,以及初始值与分区内第一个value的计算方式,规则

### 使用 Spark RDD 的 `mapValues` 方法对 Value 进行映射而不改变 Key,并保持分区不变 在 Spark 中,`mapValues` 是一种专门用于操作 RDD 中键值对(Key-Value Pair)的转换方法。它允许用户对每个键对应的值应用一个函数,而不会改变原有的键[^1]。此外,使用 `mapValues` 转换后生成的新 RDD 会继承父 RDD 的分区器分区数[^2]。 以下是一个示例代码,展示如何使用 `mapValues` 方法对 Value 进行映射: ```python from pyspark import SparkContext # 初始化 SparkContext sc = SparkContext("local", "MapValuesExample") # 创建一个包含键值对的 RDD rdd = sc.parallelize([("a", 1), ("b", 2), ("c", 3)]) # 使用 mapValues 对 Value 进行映射 mapped_rdd = rdd.mapValues(lambda x: x * 2) # 打印结果 print(mapped_rdd.collect()) ``` 在上述代码中,`mapValues` 方法将每个键对应的值乘以 2,同时保持键不变。输出结果为 `[('a', 2), ('b', 4), ('c', 6)]`[^1]。 #### 分区继承特性 当使用 `mapValues` 方法时,生成的子 RDD 会继承父 RDD 的分区器分区数。这意味着如果父 RDD 已经设置了分区器,则子 RDD 也会使用相同的分区器。以下是一个验证分区继承的示例: ```python # 设置默认并行度 conf = SparkConf().set("spark.default.parallelism", "4") sc = SparkContext(conf=conf) # 创建一个包含键值对的 RDD rdd = sc.parallelize([("a", 1), ("b", 2), ("c", 3), ("d", 4)], 4) # 使用 mapValues 对 Value 进行映射 mapped_rdd = rdd.mapValues(lambda x: x * 2) # 打印分区数分区器 print("Original RDD Partition Count:", rdd.getNumPartitions) print("Mapped RDD Partition Count:", mapped_rdd.getNumPartitions) print("Original RDD Partitioner:", rdd.partitioner) print("Mapped RDD Partitioner:", mapped_rdd.partitioner) ``` 在上述代码中,`mapped_rdd` 的分区数与父 RDD 的分区数相同,且分区器也得以继承[^2]。 ### 注意事项 - 如果需要对键进行操作,则不能使用 `mapValues`,而是需要使用 `map` 方法[^1]。 - 在分布式环境中,确保映射函数的逻辑简单高效,以避免性能瓶颈[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值