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)
    
  • 相关阅读:
    性能测试理论知识
    接口测试笔试题
    测试计划与测试报告
    java基础面试题
    软件测试人员必备的linux命令
    tomcat各目录(文件)作用
    常见的面试题
    LoadRunner中怎么设置密码参数化与用户名关联
    数据库索引总结(二)
    数据库索引总结(一)
  • 原文地址:https://www.cnblogs.com/xiaomaohai/p/6158040.html
Copyright © 2011-2022 走看看