天天看点

Spark中rdd的reduce操作的具体过程

rdd的reduce过程

rdd = sc.parallelize(range(10), 3)
diff = rdd.reduce(lambda x, y: x - y)
print('diff: %s' % diff)      
diff: 21      
# 解释下为什么结果为21:
>>> rdd.collect()
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> rdd.glom().collect()  # 获取rdd的数据,按照每个分区一个列表的形式返回一个二维列表
[[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]
# rdd.reduce(lambda x, y: x - y)的过程为
# 1. 对每个分区的元素执行一次reduce:
#    [0, 1, 2]的执行过程为(0-1)-2 = -3
#    [3,4,5]的执行过程为(3-4)-5=-6
#    [6,7,8,9]的执行过程为((6-7)-8)-9=-19
# 2. 将每个分区reduce之后的结果再次reduce,即对[-3, -6, -19]执行reduce
#    (-3- -6)- -19 = 21
# 则最终结果为21