gpt4 book ai didi

scala - 使用 Spark 将对象发送到特定分区

转载 作者:行者123 更新时间:2023-12-04 15:58:11 26 4
gpt4 key购买 nike

假设我有一个带有 nPartitions 分区的 RDD,我正在使用 mapPartitionsWithIndex 方法,同时还在驱动程序上保留一个维度为 nPartitions 的数组 x。现在假设我想将 x(i) 传送到分区 i 以便它可以在上面工作,这样做的一种天真的方法是只在闭包中调用 x(i),如以下玩具示例所示:

val sc = new SparkContext() 
val rdd = sc.parallelize(1 to 1000).repartition(10)
val nPartitions = rdd.partitions.length
val myArray = Array.fill(nPartitions)(math.random) //array to be shipped to executors
val result = rdd.mapPartitionsWithIndex((index,data) =>
Seq(data.map(_ * myArray(index)).sum).iterator
)

(忽略 mapPartitionsWithIndex 中的逻辑,只有 myArray(index) 是我们感兴趣的。但是,如果我的理解是正确的,这会将整个数组 myArray 发送给所有执行程序,因为数组在闭包中。现在,如果我们假设数组包含可能占用太多内存/序列化时间的大对象,这就会成为一个问题。

有没有办法避免这种情况,并只运送与给定执行程序中的分区相对应的数组组件?

最佳答案

这是一个过早优化的案例。如果可能的话,发送一个与分区数量一样大的数组与仅发送分区的值相比不会为您节省太多。

但是,不是将数组作为闭包发送,而是应该将数组作为
广播变量:http://spark.apache.org/docs/latest/programming-guide.html#broadcast-variables

主要区别在于闭包是序列化的并为每个任务发送出去,而从文档页面“广播变量允许程序员在每台机器上缓存一个只读变量,而不是发送它的副本任务”。

关于scala - 使用 Spark 将对象发送到特定分区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34413315/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com