RDD.isEmpty() https://issues.apache.org/jira/browse/SPARK-5270将成为 Spark 1.3.0 的一部分。
根据中的建议这个 apache 邮件线程 http://mail-archives.apache.org/mod_mbox/spark-user/201402.mbox/%3CCAKDwOakbF9pop+pN8XzF6iT1OPc383+aWcTf2a6t=rH8srxRLg@mail.gmail.com%3E以及后来对这个答案的一些评论,我做了一些小的本地实验。最好的方法是使用take(1).length==0
.
def isEmpty[T](rdd : RDD[T]) = {
rdd.take(1).length == 0
}
它应该运行在O(1)
除非 RDD 为空,在这种情况下,它的分区数量是线性的。
感谢乔什·罗森和尼克·查马斯向我指出了这一点。
注意:如果 RDD 类型为RDD[Nothing]
e.g. isEmpty(sc.parallelize(Seq()))
,但这在现实生活中可能不是问题。isEmpty(sc.parallelize(Seq[Any]()))
工作正常。
Edits:
-
Edit 1: Added
take(1)==0
方法,感谢评论。
我原来的建议: Use mapPartitions
.
def isEmpty[T](rdd : RDD[T]) = {
rdd.mapPartitions(it => Iterator(!it.hasNext)).reduce(_&&_)
}
它应该扩大分区的数量,并且不像take(1)
。然而,它对于 RDD 类型来说是鲁棒的RDD[Nothing]
.
实验:
我用这个代码来计时。
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