pyspark - pyspark sql sum vs aggr
问题描述
以下哪个是 Pyspark 中更好的方法?
第二个查询是否比 PySpark 中的第一个查询(在集群模式下)有任何优势/性能提升?
#1) without using aggr
total_distance_df = spark.sql("SELECT sum(distance) FROM flights")\
.withColumnRenamed('sum(CAST(distance AS DOUBLE))', 'total_distance')
total_distance_df.show()
Vs
#2) with using aggr
total_distance_df = spark.sql("SELECT distance FROM flights")\
.agg({"distance":"sum"})\
.withColumnRenamed("sum(distance)","total_distance")
total_distance_df.show()
解决方案
两者都是相同的,请检查explain
查询计划以查看任何差异。
Example:
#sample df
df1.show()
+---+--------+
| id|distance|
+---+--------+
| a| 1|
| b| 2|
+---+--------+
df1.createOrReplaceTempView("tmp")
spark.sql("SELECT sum(distance) FROM tmp").withColumnRenamed('sum(CAST(distance AS DOUBLE))', 'total_distance').explain()
#== Physical Plan ==
#*(2) HashAggregate(keys=[], functions=[sum(distance#179L)])
#+- Exchange SinglePartition
# +- *(1) HashAggregate(keys=[], functions=[partial_sum(distance#179L)])
# +- *(1) Project [distance#179L]
# +- Scan ExistingRDD[id#178,distance#179L]
spark.sql("SELECT distance FROM tmp").agg({"distance":"sum"}).explain()
#== Physical Plan ==
#*(2) HashAggregate(keys=[], functions=[sum(distance#179L)])
#+- Exchange SinglePartition
# +- *(1) HashAggregate(keys=[], functions=[partial_sum(distance#179L)])
# +- *(1) Project [distance#179L]
# +- Scan ExistingRDD[id#178,distance#179L]
如您所见,SUM 和 aggr 的计划相似。
推荐阅读
- python - 当我使用烧瓶 + uwsgi + nginx 将烧瓶部署到服务器时,多进程无法在烧瓶中工作
- android - React Native Video,如何动态更改源?
- python - 从较大列表中提取子列表后,如何获取列表中元素的跨度?
- php - 聊天消息以相反的顺序显示
- ruby - Ruby - 获取本地文件的 UNC 路径
- r - 根据其他变量是否为“是”,使用“是/否”创建新变量。变异?
- visual-studio - @INC 中的 Win32/Process.pm 是什么?
- if-statement - 最大日期,基于不同的列
- python - 错误'numpy.float64'对象在应用函数后没有属性'shift'
- mysql - 错误 2002 (HY000): 无法连接到“192.168.1.15”上的 MySQL 服务器 (115)