Spark:测试RDD是否为空的有效方法 [英] Spark: Efficient way to test if an RDD is empty
本文介绍了Spark:测试RDD是否为空的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
RDD上没有isEmpty
方法,那么测试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为空时除外,在这种情况下,它与分区数成线性关系。
感谢乔什·罗森和尼克·钱马斯给我指出了这一点。
注意:如果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
这篇关于Spark:测试RDD是否为空的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文