Skip to main content
 首页 » 编程设计

python之保存我的 Apache Spark 管道的中间状态

2024年10月01日33zdz8207

我有一个非常复杂的 Apache PySpark 管道,它对一组(非常大的)文本文件执行多个转换。我的管道的预期输出是管道的不同阶段。哪种方法最好(即更高效但也更闪耀,在某种意义上:更适合 Spark 编程模型和风格)?

现在,我的代码如下所示:

# initialize the pipeline and perform the first set of transformations. 
ctx = pyspark.SparkContext('local', 'MyPipeline') 
rdd = ctx.textFile(...).map(...).map(...) 
 
# first checkpoint: the `first_serialization` function serializes 
# the data into properly formatted string.  
rdd..map(first_serialization).saveAsTextFile("ckpt1") 
 
# here, I have to read again from the previously saved checkpoint 
# using a `first_deserialization` function that deserializes what has 
# been serialized from the `firs_serialization` function. Then performs 
# other transformations. 
rdd = ctx.textFile("ckpt1").map(...).map(...) 

等等。我想摆脱序列化方法和多次保存/读取——顺便说一下,它会影响效率吗?我想是的。

有什么提示吗? 提前致谢。

请您参考如下方法:

这看起来显然很简单,因为确实如此,但我建议在继续重用现有 RDD 的同时写出中间阶段(边栏:使用数据集/数据帧而不是 RDD 以获得更高的性能)并继续处理,写出中间结果,你去。

当您已经处理数据(理想情况下甚至缓存!)以供进一步使用时,无需支付从磁盘/网络读取的代价。

使用您自己的代码的示例:

# initialize the pipeline and perform the first set of transformations. 
ctx = pyspark.SparkContext('local', 'MyPipeline') 
rdd = ctx.textFile(...).map(...).map(...) 
 
# first checkpoint: the `first_serialization` function serializes 
# the data into properly formatted string.  
string_rdd = rdd..map(first_serialization) 
string_rdd.saveAsTextFile("ckpt1") 
 
# reuse the existing RDD after writing out the intermediate results 
rdd = rdd.map(...).map(...) # rdd here is the same variable we used to create the string_rdd results above. alternatively, you may want to use the string_rdd variable here instead of the original rdd variable.