spark小技巧-mapPartitions
2024-09-18 10:35:09
与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)
最新文章
- Centos7 修改ssh 默认端口号
- 组合or继承
- IO流-概览
- 打开网页自动弹出qq客户端
- vc6静态库的生成和调用
- Python进阶之闭包
- Cacti+Nagios监控平台完美整合
- easyui tree 判断是否是叶子节点
- LeetCode OJ 223.Rectangle Area
- UVA732【DFS+栈】
- 使用Spring+Junit4.4进行测试
- js逗号表达式
- Net Core API网关Ocelot
- 利用salt搭建hadoop集群
- 使用 Azure 资源管理器向 Windows VM 应用策略
- 【亲测有效】Win10家庭版Microsoft Edge页面出现乱码的两种解决方案及gpedit.msc命令无法使用的解决策略
- 缩减apk大小
- C# Timer自带定时器
- java技术秘籍 转摘
- ftm时钟源
热门文章
- percona
- 获取表单的初始值,模拟placeholder属性
- 判断webkit中的js引擎是否是v8
- [Stanford 2011] Views 知识点
- Payoneer欧洲收款账户开通激活及使用-用于接收欧洲公司资金和欧元收款
- [LeetCode]题解(python):060-Permutation Sequence
- [LeetCode]题解(python):030-Substring with Concatenation of All Words
- iOS开发中 在MRC中让某些类使用ARC编译 或者相反
- [代码片段]读取BMP文件
- AJAX中UPDATEPANEL配合TIMER控件实现局部无刷新