Spark算子[03]:mapPartitions,mapPartitionsWithIndex 源码实战案例分析

博客详细介绍了Spark的mapPartitions和mapPartitionsWithIndex算子,强调了它们与map的区别,特别是在处理大规模数据时的效率优势。通过Scala和Java实例展示了如何使用这两个函数,并提到了使用时需要注意的优化点,包括可能引发的OOM问题。
摘要由CSDN通过智能技术生成

mapPartitions

  • 该函数和map函数类似,只不过映射函数的参数由RDD中的每一个元素变成了RDD中每一个分区的迭代器。如果在映射的过程中需要频繁创建额外的对象,使用mapPartitions要比map高效的过。
  • 比如,将RDD中的所有数据通过JDBC连接写入数据库,如果使用map函数,可能要为每一个元素都创建一个connection,这样开销很大,如果使用mapPartitions,那么只需要针对每一个分区建立一个connection。
  • 参数preservesPartitioning表示是否保留父RDD的partitioner分区信息。
  /**
   * 通过将一个函数应用于这个RDD的每个分区,返回一个新的RDD。
   * `preservesPartitioning`指示输入函数是否保留分区
   */
  def mapPartitions[U: ClassTag](
      f: Iterator[T] => Iterator[U],
      preservesPartitioning: Boolean = false): RDD[U] = withScope {
    val cleanedF = sc.clean(f)
    new MapPartitionsRDD(
      this,
      (context: TaskContext, index: Int, iter: Iterator[T]) => cleanedF(iter),
      preservesPartitioning)
  }

mapPartitionsWithIndex

  • 函数作用同mapPartitions,不过提供了两个参数,第一个参数为分区的索引。
  /**
   * 通过在RDD的每个分区上应用一个函数来返回一个新的RDD,同时跟踪原始分区的索引。
   */
  def mapPartitionsWithIndex[U: ClassTag](
      f: (Int, Iterator[T]) => Iterator[U],
      preservesPartitioning: Boolean = false): RDD[U] = withScope {
    val cleanedF = sc.clean(f)
    new MapPartitionsRDD(
      this,
      (context: TaskContext, index: Int, iter: Iterator[T]) => cleanedF(index, iter),
      preservesPartitioning)
  }

Scala实例

object Core005 {
   
  def main(args: Array[String]) {
    val conf = new SparkConf().setMaster("local").setAppName("core05")
    val sc = new SparkContext(conf)
    val rdd = sc.parallelize(List(1, 2, 3, 4, 5), 2)
    //类似Java的mapPartitionsToPair
    val rdd1 = rdd.mapPartitions(ite => {
      val list = new ListBuffer[Tuple2[Integer, Integer]](); //scala.collection.mutable.ListBuffer
      while (ite.hasNext) {
        val next = ite.next()
        list += Tuple2(next, next * 2)
      }
      list.iterator
    }, false)

    rdd1.foreach(x => print(x + " "))

结果:(1,2) (2,4) (3,6) (4,8) (5,10)

    //mapPartitions
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

生命不息丶折腾不止

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值