Action:
执行一些action操作需要导入一些模块
from operator import add
from operator import mul
from operator import mod
1、collect
2、saveAsText
3、first:
返回第一个RDD元素 :first=take(1)
4、take:
取前N个数值,Take the first num elements of the RDD.
Examples :
>>> sc.parallelize([2, 3, 4, 5, 6]).cache().take(2)
[2, 3]
5、top:
取topN Get the top N elements from an RDD.
Examples :
>>> sc.parallelize([2, 3, 4, 5, 6], 2).top(2)
[6, 5]
6、takeSample:
takeSample(self, withReplacement, num, seed=None)
Examples :0-10范围取数,取20个数,种子=1
>>> rdd = sc.parallelize(range(0, 10))
>>> len(rdd.takeSample(True, 20, 1)) 20
7、foreach():
Examples :
>>> def f(x): print(x)
>>> sc.parallelize([1, 2, 3, 4, 5]).foreach(f)
等价于
>>> rdd2.foreach(lambda x:print(x))
8、coalesce:
用来指定分区的加减,如果加减的分区超过了第一开始指定的分区数,coalesce()指定的分区数不生效,需要开启Fasle使分区重新shuffle:coalesce(self, numPartitions, shuffle=False)
9、fold:
fold: 等价于 aggregate
( zeroValue:自然值, seqOp:分区内, combOp:分区间)=fold(自然值,分区内分区间)
计算所有分区的结果返回一个值,fold内含有自然值,在进行operator操作时候,会在分区内与分区间进行fold操作
例:自然值为1 总共三个分区,则每个分区内都会加上1 然后所有的分区间再加上1 。因此,总共加上4
rdd1 = sc.parallelize([1,2,3,4,5,6],3)
rdd2 = rdd1.fold(1,add)
print('no fold:',rdd1.reduce(add)) # 21
print('fold:',rdd2) # 25
10、reduce:
执行算子,搭配 operator 使用
rdd4 = sc.parallelize([1,2,3,4,5,6])
print(rdd4.reduce(add)) #21