Apache spark sparksql中的递归cte
你能帮我在SPARK SQL中实现同样的功能吗?使用SPARK SQL是不可能的。WITH子句存在,但不适用于类似于ORACLE中的CONNECT BY或DB2中的递归 这已经很晚了,但今天我尝试使用pysparksql实现cte递归查询 这里,我有一个简单的数据帧。我想做的是找到每个ID的最新ID 原始数据帧:Apache spark sparksql中的递归cte,apache-spark,apache-spark-sql,spark-notebook,Apache Spark,Apache Spark Sql,Spark Notebook,你能帮我在SPARK SQL中实现同样的功能吗?使用SPARK SQL是不可能的。WITH子句存在,但不适用于类似于ORACLE中的CONNECT BY或DB2中的递归 这已经很晚了,但今天我尝试使用pysparksql实现cte递归查询 这里,我有一个简单的数据帧。我想做的是找到每个ID的最新ID 原始数据帧: ; WITH Hierarchy as ( select distinct PersonnelNumber , Em
; WITH Hierarchy as
(
select distinct PersonnelNumber
, Email
, ManagerEmail
from dimstage
union all
select e.PersonnelNumber
, e.Email
, e.ManagerEmail
from dimstage e
join Hierarchy as h on e.Email = h.ManagerEmail
)
select * from Hierarchy
我想要的结果是:
+-----+-----+
|OldID|NewID|
+-----+-----+
| 1| 2|
| 2| 3|
| 3| 4|
| 4| 5|
| 6| 7|
| 7| 8|
| 9| 10|
+-----+-----+
这是我的密码:
+-----+-----+
|OldID|NewID|
+-----+-----+
| 1| 5|
| 2| 5|
| 3| 5|
| 4| 5|
| 6| 8|
| 7| 8|
| 9| 10|
+-----+-----+
我知道性能相当差,但至少它给出了我需要的答案
这是我第一次向StackOverFlow发布答案,如果我有任何错误,请原谅。这是否回答了您的问题?请参阅答案评论。谢谢您的回复。它可能不是类似的通用表表达式方法,但有什么不同的方法来实现这一点吗?比如写一些函数并调用它们..仍然在探索我这边的选项。试试这个bug,它也是程序性的。我相信我的回答正如你所问的那样足够了,但不是上面的错误
df = sqlContext.createDataFrame([(1, 2), (2, 3), (3, 4), (4, 5), (6, 7), (7, 8),(9, 10)], "OldID integer,NewID integer").checkpoint().cache()
dfcheck = df.drop('NewID')
dfdistinctID = df.select('NewID').distinct()
dfidfinal = dfdistinctID.join(dfcheck, [dfcheck.OldID == dfdistinctID.NewID], how="left_anti") #We find the IDs that have not been replaced
dfcurrent = df.join(dfidfinal, [dfidfinal.NewID == df.NewID], how="left_semi").checkpoint().cache() #We find the the rows that are related to the IDs that have not been replaced, then assign them to the dfcurrent dataframe.
dfresult = dfcurrent
dfdifferentalias = df.select(df.OldID.alias('id1'), df.NewID.alias('id2')).checkpoint().cache()
while dfcurrent.count() > 0:
dfcurrent = dfcurrent.join(broadcast(dfdifferentalias), [dfcurrent.OldID == dfdifferentalias.id2], how="inner").select(dfdifferentalias.id1.alias('OldID'), dfcurrent.NewID.alias('NewID')).cache()
dfresult = dfresult.unionAll(dfcurrent)
display(dfresult.orderBy('OldID'))