Spark算子:foreach和foreachPartition

本文探讨了Spark中的两个重要行动操作——foreach和foreachPartition。它们用于处理RDD的每个partition,区别在于foreach直接对每条数据应用函数,而foreachPartition则将函数应用于每个partition的iterator。在实践中,foreachPartition由于可以更有效地处理数据,例如批量插入数据库,从而在性能上有显著优势。
摘要由CSDN通过智能技术生成

RDD.foreachPartition/foreach这两个action的操作: 
这两个action主要用于对每个partition中的iterator实行迭代的处理。通过用户传入的function对iterator进行内容的处理。

foreach的操作

由下面的源码中,foreach操作是直接调迭代rdd中每一条数据进行function操作。

 /**
   * Applies a function f to all elements of this RDD.
   * 将函数应用在RDD的所有元素;
   */
  def foreach(f: T => Unit): Unit = withScope {
    val cleanF = sc.clean(f)
    //runJob job的运行
    sc.runJob(this, (iter: Iterator[T]) => iter.foreach(cleanF))
  }

foreachPartition操作

这个函数也是根据传入的function进行处理,但不同处在于,这里function的传入参数是一个partition对应数据的iterator,而不是直接使用iterator的foreach。

/**
   * Applies a function f to each partition of this RDD.
   * 将函数f应用于该RDD的每个分区。
   */
  def foreachPartition(f: Iterator[T] => Unit): Unit = withScope {
    val cleanF = sc.clean(f)
    sc.runJob(this, (iter: Iterator[T]) =&g
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值