Spark官方文档中解释为:
seqOp操作会聚合各分区中的元素,然后combOp操作把所有分区的聚合结果再次聚合,两个操作的初始值都是zeroValue. seqOp的操作是遍历分区中的所有元素(T),第一个T跟zeroValue做操作,结果再作为与第二个T做操作的zeroValue,直到遍历完整个分区。combOp操作是把各分区聚合的结果,再聚合。aggregate函数返回一个跟RDD不同类型的值。因此,需要一个操作seqOp来把分区中的元素T合并成一个U,另外一个操作combOp把所有U聚合。
-
zeroValue
-
the initial value for the accumulated result of each partition for the
seqOp
operator, and also the initial value for the combine results from different partitions for thecombOp
operator - this will typically be the neutral element (e.g.Nil
for list concatenation or0
for summation)
seqOp
-
an operator used to accumulate results within a partition
combOp
-
an associative operator used to combine results from different partitions
zeroValue为(0,0)时很好理解,seqOp可以理解为求和,combOp可以理解为求个数,如果要计算均值的话直接拿结果的45/9就可以得到5,具体过程如下;
1. 0+1, 0+1
2. 1+2, 1+1
3. 3+3, 2+1
4. 6+4, 3+1
5. 10+5, 4+1
6. 15+6, 5+1
7. 21+7, 6+1
8. 28+8, 7+1
9. 36+9, 8+1
4、>>> sc.parallelize([1, 2, 3, 4,5,6,7,8,9]).aggregate((1, 1), seqOp, combOp)
(50,14)
一开始怎么也理解不了怎么出来的这个结果,后来发现是因为spark自动分为4个区了(这个要看spark集群的默认设置)
5、>>> sc.parallelize([1, 2, 3, 4,5,6,7,8,9],4).aggregate((1, 1), seqOp, combOp)
(50,14)
6、>>> sc.parallelize([1, 2, 3, 4,5,6,7,8,9],1).aggregate((1, 1), seqOp, combOp)
(47,11)
seqOp分区内的计算过程:
1. 1+1, 1+1
2. 2+2, 2+1
3. 4+3, 3+1
4. 7+4, 4+1
5. 11+5, 5+1
6. 16+6, 6+1
7. 22+7, 7+1
8. 29+8, 8+1
9. 37+9, 9+1
结果为(46,10)
combOp聚合不同分区的过程为(1,1) + (46,10)
结果为: (47,11)
7、>>> sc.parallelize([1, 2, 3, 4,5,6,7,8,9],2).aggregate((1, 1), seqOp, combOp)
(48,12)
seqOp过程如下:
分区1: 1,2,3,4
1. 1+1, 1+1
2. 2+2, 2+1
3. 4+3, 3+1
4. 7+4, 4+1
结果为(11,5)
分区2: 5,6,7,8,9
5. 1+5, 1+1
6. 6+6, 2+1
7. 12+7, 3+1
8. 19+8, 4+1
9. 27+9, 5+1
结果为:(36,6)
combOp过程如下:(1,1)+(11,5) + (36,6) = (48,12)