如何使这段代码在Spark中更有效?
我需要根据数据计算最小值、最大值、计数和平均值。
这是我的样本数据
Name Shop Money
A Shop001 99.99
A Shop001 87.15
B Shop001 3.99
...
现在,我尝试组织我的数据,生成mean、min、max、count by Name+Shop(key)。
然后通过collect()获得结果。
这是我在spark中的代码
def tupleDivide(y):
return float(y[0])/y[1]
def smin(a, b):
return min(a, b)
def smax(a, b):
return max(a, b)
raw = sgRDD.map(lambda x: getVar(parserLine(x),list_C+list_N)).cache()
cnt = raw.map(lambda (x,y,z): (x+"_"+y, 1)).countByKey()
sum = raw.map(lambda (x,y,z): (x+"_"+y, z)).reduceByKey(add)
min = raw.map(lambda (x,y,z): (x+"_"+y, z)).reduceByKey(smin)
max = raw.map(lambda (x,y,z): (x+"_"+y, z)).reduceByKey(smax)
raw_cntRDD = sc.parallelize(cnt.items(),3)
raw_mean = sum.join(raw_cntRDD).map(lambda (x, y): (x, tupleDivide(y)))
有人能提供一些关于优雅的编码风格的建议吗?
谢谢!在
您应该使用
aggregateByKey
来获得更优化的处理。其思想是存储由count、min、max和sum组成的state
向量,并使用聚合函数来获得最终值。另外,可以使用元组作为键,不必将键连接到单个字符串中。在相关问题 更多 >
编程相关推荐