spark小技巧-mapPartitions
2015-09-21 16:03
405 查看
与map方法类似,map是对rdd中的每一个元素进行操作,而mapPartitions(foreachPartition)则是对rdd中的每个分区的迭代器进行操作。如果在map过程中需要频繁创建额外的对象(例如将rdd中的数据通过jdbc写入数据库,map需要为每个元素创建一个链接而mapPartition为每个partition创建一个链接),则mapPartitions效率比map高的多。
SparkSql或DataFrame默认会对程序进行mapPartition的优化。
比如:输入2,结果(2,4)
结果
结果
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)
相关文章推荐
- spark小技巧-mapPartitions
- spark小技巧-mapPartitions
- android开发步步为营之77:android数据库ORM之greenDAO
- spark小技巧-mapPartitions
- Android-在线查看源码
- ios 资料
- Android开源组件SlidingMenu的基本使用方法和SlidingMenuDemo
- XCode7和ios9的兼容和更新问题解决方案
- Android中常见的像素单位
- android获取系统wifi状态等
- Android Studio快捷键设置
- 【android】通过leakCanary找出程序内存泄露点
- Android布局优化之<merge>与<ViewStub>标签使用
- Objective-C 快速入门
- Android自定义View示例(一)—带有删除按钮的EditText
- How to embed an icon in a Qt application
- Android快速开发工具GsonFormat使用教程
- android弹出下拉选择菜单,单选,多选【运行截图——图】
- android Bitmap getByteCount和getRowBytes
- android studio集成svn