gpt4 book ai didi

scala - Spark : Efficient way to test if an RDD is empty

转载 作者:行者123 更新时间:2023-12-03 10:26:52 26 4
gpt4 key购买 nike

没有 isEmpty RDD 上的方法,那么测试 RDD 是否为空的最有效方法是什么?

最佳答案

RDD.isEmpty() 将成为 Spark 1.3.0 的一部分。

基于 this apache mail-thread 中的建议后来对这个答案的一些评论,我做了一些小的本地实验。最好的方法是使用 take(1).length==0 .

def isEmpty[T](rdd : RDD[T]) = {
rdd.take(1).length == 0
}

它应该在 O(1) 中运行除非 RDD 为空,在这种情况下,它与分区数呈线性关系。

感谢 Josh Rosen 和 Nick Chammas 向我指出这一点。

注意:如果 RDD 的类型是 RDD[Nothing],这将失败例如 isEmpty(sc.parallelize(Seq())) ,但这在现实生活中可能不是问题。 isEmpty(sc.parallelize(Seq[Any]()))工作正常。

编辑:
  • 编辑 1:已添加 take(1)==0方法,感谢评论。

  • 我最初的建议:使用 mapPartitions .
    def isEmpty[T](rdd : RDD[T]) = {
    rdd.mapPartitions(it => Iterator(!it.hasNext)).reduce(_&&_)
    }

    它应该在分区数量上进行扩展,并且不像 take(1) 那样干净。 .然而,它对 RDD[Nothing] 类型的 RDD 来说是健壮的。 .

    实验:

    我使用此代码进行计时。
    def time(n : Long, f : (RDD[Long]) => Boolean): Unit = {
    val start = System.currentTimeMillis()
    val rdd = sc.parallelize(1L to n, numSlices = 100)
    val result = f(rdd)
    printf("Time: " + (System.currentTimeMillis() - start) + " Result: " + result)
    }

    time(1000000000L, rdd => rdd.take(1).length == 0L)
    time(1000000000L, rdd => rdd.mapPartitions(it => Iterator(!it.hasNext)).reduce(_&&_))
    time(1000000000L, rdd => rdd.count() == 0L)
    time(1000000000L, rdd => rdd.takeSample(true, 1).isEmpty)
    time(1000000000L, rdd => rdd.fold(0)(_ + _) == 0L)

    time(1L, rdd => rdd.take(1).length == 0L)
    time(1L, rdd => rdd.mapPartitions(it => Iterator(!it.hasNext)).reduce(_&&_))
    time(1L, rdd => rdd.count() == 0L)
    time(1L, rdd => rdd.takeSample(true, 1).isEmpty)
    time(1L, rdd => rdd.fold(0)(_ + _) == 0L)

    time(0L, rdd => rdd.take(1).length == 0L)
    time(0L, rdd => rdd.mapPartitions(it => Iterator(!it.hasNext)).reduce(_&&_))
    time(0L, rdd => rdd.count() == 0L)
    time(0L, rdd => rdd.takeSample(true, 1).isEmpty)
    time(0L, rdd => rdd.fold(0)(_ + _) == 0L)

    在我有 3 个工作核心的本地机器上,我得到了这些结果
    Time:    21   Result: false
    Time: 75 Result: false
    Time: 8664 Result: false
    Time: 18266 Result: false
    Time: 23836 Result: false

    Time: 113 Result: false
    Time: 101 Result: false
    Time: 68 Result: false
    Time: 221 Result: false
    Time: 46 Result: false

    Time: 79 Result: true
    Time: 93 Result: true
    Time: 79 Result: true
    Time: 100 Result: true
    Time: 64 Result: true

    关于scala - Spark : Efficient way to test if an RDD is empty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28454357/

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