apache-spark - Spark SQL 中分组依据和窗口函数如何交互?
问题描述
从这个问题中,我了解到窗口函数是在 PostgresSQL 中按函数分组之后评估的。
我想知道当您在 Spark 的同一查询中使用 group by 和 window 函数时会发生什么。我和上一个问题的发帖人有同样的问题:
- 选定的行是否首先分组,然后由窗口函数考虑?
- 还是先执行窗口函数,然后将结果值按group by分组?
- 还有什么?
解决方案
如果您在同一查询中有窗口和分组依据,那么
Group by 执行
first
然后window
函数将应用于 groupby 数据集。您可以查看查询解释计划以获取更多详细信息。
Example:
//sample data
spark.sql("select * from tmp").show()
//+-------+----+
//|trip_id|name|
//+-------+----+
//| 1| a|
//| 2| b|
//+-------+----+
spark.sql("select row_number() over(order by trip_id),trip_id,count(*) cnt from tmp group by trip_id").explain()
//== Physical Plan ==
//*(4) Project [row_number() OVER (ORDER BY trip_id ASC NULLS FIRST ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)#150, trip_id#10, cnt#140L]
//+- Window [row_number() windowspecdefinition(trip_id#10 ASC NULLS FIRST, specifiedwindowframe(RowFrame, unboundedpreceding$(), currentrow$())) AS row_number() OVER (ORDER BY //trip_id ASC NULLS FIRST ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)#150], [trip_id#10 ASC NULLS FIRST]
// +- *(3) Sort [trip_id#10 ASC NULLS FIRST], false, 0
// +- Exchange SinglePartition
// +- *(2) HashAggregate(keys=[trip_id#10], functions=[count(1)])
// +- Exchange hashpartitioning(trip_id#10, 200)
// +- *(1) HashAggregate(keys=[trip_id#10], functions=[partial_count(1)])
// +- LocalTableScan [trip_id#10]
*(2) groupby executed first
*(4) window function applied on the result of grouped dataset.
如果您有窗口子句subquery
并且外部查询有分组,则首先执行子查询(窗口),然后执行外部查询(分组)。
Ex:
spark.sql("select trip_id,count(*) from(select *,row_number() over(order by trip_id)rn from tmp)e group by trip_id ").explain()
推荐阅读
- python - 如何在 azure 构建管道中添加 --no-bundler 命令
- bluetooth-lowenergy - Gatttool 非交互模式,多个 char-write-req
- java - 如何在两个字符之间获取字符串(例如“|this|that|”)
- php - laravel 所有路由都在下载索引文件
- angular - 在 Angular 8 中,如何将动态数据从可观察对象传递到模态对话框?
- spring-boot - Spring Cloud Stream 错误处理...错误
- google-play - Google Play Store SubscriptionPurchase.Get API 响应说明
- c# - Websocket连接 - 一段时间后没有收到消息C#
- vmware - 通过 Pyvmomi 获取 Esxi 网络使用情况
- php - 在网站上显示文件的扩展名是否安全?