概念:
map:通过函数func传递源的每个元素来形成一个新的分布式数据集。
mapPartitions:与map类似,但是在RDD的每个分区(块)上分别运行,所以func在类型T的RDD上运行时必须是Iterator <T> => Iterator <U>类型。
mapPartitionsWithIndex:类似于mapPartitions,但也提供func代表分区索引的整数值,所以func在T型RDD上运行时必须是(Int,Iterator <T>)=> Iterator <U>类型。
官网案例:
map:
>>> rdd = sc.parallelize(["b", "a", "c"])
>>> sorted(rdd.map(lambda x: (x, 1)).collect())
[('a', 1), ('b', 1), ('c', 1)]
从案例里面看出,map是针对每个元素操作的,返回的数据集和原始数据数量上保持一致。
mapPartitions:
>>> rdd = sc.parallelize([1, 2, 3, 4], 2)
>>> def f(iterator): yield sum(iterator)
>>> rdd.mapPartitions(f).collect()
[3, 7]
从案例可以看出,是将分区中的数据都计算完毕后返回,减少了数据访问的次数。提高了效率。
mapPartitionsWithIndex:
>>> rdd = sc.parallelize([1, 2, 3, 4], 4)
>>> def f(splitIndex, iterator): yield splitIndex
>>> rdd.mapPartitionsWithIndex(f).sum()
6
从案例来看,索引是从0开始的,可以通过索引知道数据在哪个分区里面跑。