在火星内部观看this非常好的视频,演示者说,除非在缓存后对RDD执行操作,否则缓存不会真正发生。
我从未在任何其他情况下看到count()被调用。所以,我猜测他只是在cache()之后调用count()来强制执行他给出的简单示例中的持久性。每次在一个代码中调用cache()或persist()时都没有必要这样做。这是对的吗?
答案 0 :(得分:2)
除非在缓存后对某个RDD执行操作,否则缓存不会真正发生。
这是100%的真实。方法cache
/ persist
只会标记RDD以进行缓存。只要在RDD上调用操作,就会缓存RDD中的项目。
...只在cache()之后调用count()来强制执行他给出的简单示例中的持久性。每次在一个代码中调用cache()或persist()时都没有必要这样做。这是对的吗?
你再次100%正确。但我会详细说明这一点。
为便于理解,请考虑以下示例。
rdd.cache()
rdd.map(...).flatMap(...) //and so on
rdd.count() //or any other action
假设您的RDD中有10个文档。运行上述代码段后,每个文档都会执行以下任务:
另一方面,
rdd.cache().count()
rdd.map(...).flatMap(...) //and so on
rdd.count() //or any other action
运行上述代码段时,首先缓存所有10个文档(整个RDD )。然后应用map函数和flatMap函数。
两者都是正确的,并按照要求使用。 希望这会使事情变得更加清晰。
答案 1 :(得分:0)
.cache()
和.persist()
都是转换(不是动作),因此当您调用它们时,请将其添加到DAG中。如下图所示,缓存/持久的rdd / dataframe的点中为绿色。
经过大量转换后,您有一个动作(.count()
,.save()
,.show()
等),没关系,您也立即有另一个动作。
基于@code的示例:
// 1 CASE: cache/persist the initial rdd
rdd.cache()
rdd.count() // It forces the cache but it DOESNT need because we have the 2nd count.
rdd.map(...).flatMap(...) # Transformations
rdd.count() //or any other action
// 2 CASE: cache/persist the transformed rdd
rdd.map(...).flatMap(...) # Transformations
rdd.cache()
rdd.count() //or any other action
我的观点是,如果不需要操作的结果,请不要强制执行缓存/持久性,因为您计算出的东西是无用的。