zoukankan      html  css  js  c++  java
  • spark小技巧-mapPartitions

    与map方法类似,map是对rdd中的每一个元素进行操作,而mapPartitions(foreachPartition)则是对rdd中的每个分区的迭代器进行操作。如果在map过程中需要频繁创建额外的对象(例如将rdd中的数据通过jdbc写入数据库,map需要为每个元素创建一个链接而mapPartition为每个partition创建一个链接),则mapPartitions效率比map高的多。

    SparkSql或DataFrame默认会对程序进行mapPartition的优化。

    Demo

    实现将每个数字变成原来的2倍的功能

    比如:输入2,结果(2,4)

    使用map

    val a = sc.parallelize(1 to 9, 3)
    def mapDoubleFunc(a : Int) : (Int,Int) = {
        (a,a*2)
    }
    val mapResult = a.map(mapDoubleFunc)
    
    println(mapResult.collect().mkString)

    结果

    (1,2)(2,4)(3,6)(4,8)(5,10)(6,12)(7,14)(8,16)(9,18)
    

    使用mapPartitions

    val a = sc.parallelize(1 to 9, 3)
      def doubleFunc(iter: Iterator[Int]) : Iterator[(Int,Int)] = {
        var res = List[(Int,Int)]()
        while (iter.hasNext)
        {
          val cur = iter.next;
          res .::= (cur,cur*2)
        }
        res.iterator
      }
    val result = a.mapPartitions(doubleFunc)
    println(result.collect().mkString)

    结果

    (3,6)(2,4)(1,2)(6,12)(5,10)(4,8)(9,18)(8,16)(7,14)
    
  • 相关阅读:
    mybatis的知识点总结
    orm框架与缓存的关系
    mybatis知识点
    mybatis
    MyBatis的动态SQL详解
    工资谈判技巧
    MySQL 创建函数(Function)
    开始AFNetworking
    hdu 4778 Rabbit Kingdom(减少国家)
    设计模式:代理模式
  • 原文地址:https://www.cnblogs.com/zhangyunlin/p/6168166.html
Copyright © 2011-2022 走看看