Apache spark 2个操作的最后一个公共部分是否需要spark缓存?

Apache spark 2个操作的最后一个公共部分是否需要spark缓存?,apache-spark,pyspark,apache-spark-sql,Apache Spark,Pyspark,Apache Spark Sql,我的代码: df1 = sql_context.sql("select * from table1") #should I cache here? df2 = sql_context.sql("select * from table2") #should I cache here? df1 = df1.where(df1.id == '5') df1 = df1.where(df1.city == 'NY') joined_df = df1.join(df

我的代码:

df1 = sql_context.sql("select * from table1") #should I cache here?
df2 = sql_context.sql("select * from table2") #should I cache here?
df1 = df1.where(df1.id == '5')
df1 = df1.where(df1.city == 'NY')
joined_df = df1.join(df2, on = "key") # should I cache here?
output_df = joined_df.where(joined_df.x == 5)
joined_df.write.format("csv").save(path1)
output_df.write.format("csv").save(path2)
因此,我在代码中有两个操作,它们都在df1上生成过滤器,并将数据与df2连接起来。
在此代码中使用cache()的正确位置在哪里?
我是否应该缓存df1和df2,因为它们将在这两个操作中使用。

或者我应该只缓存这两个操作之间最后一个公共部分的连接的df吗?

我认为唯一值得调用缓存的地方是
df1=df1.where(df1.city=='NY').cache()
。可能您还希望在
joined_df=df1.join(df2,on=“key”).cache()上进行缓存,因为
joined_df
用于两个后续操作。但Spark自身的优化很可能会使此注释在某些方面无效。@ernest_k如果我只缓存加入的_df,我希望Spark能够进行完全优化,但我只是想确保这是真的,你实际上是对的,我认为
df1
的使用超出了声明
joined_df
的范围。因此,是的,我只希望在这段代码中加入
join\u df=df1.join(df2,on=“key”).cache()。但这仅在创建
joined\u df
后不使用
df1
df2
时有效。这是否回答了您的问题?我的建议是,只有当缓存对美国有很大好处时,才使用缓存。缓存有太多的缺点-可能的磁盘空间问题,禁用AQE(spark 3+),在许多情况下它会减慢速度。因此,您需要确保在您的用例中有真正的性能提升。