2016-02-24 132 views
2

元素我怎样才能有效地从字符串的RDD随机选择一个元素?获得来自RDD

+0

我做到了,在一些非无意义的方式通过映射RDD到zipWithIndex和使用随机的。与计数洗牌和拾取索引 –

+2

['takeSample'](https://spark.apache.org/docs/1.5.2/api/scala/index.html#org.apache.spark.rdd.RDD)? –

回答

6

你需要使用takeSample。例如:

val data = sc.parallelize(Range(1,100)) 
// data: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[9] at parallelize at <console>:27 

data.takeSample(false,1) 
// res9: Array[Int] = Array(38) 

data.takeSample(false,1) 
// res10: Array[Int] = Array(72) 

data.takeSample(false,1) 
// res11: Array[Int] = Array(93) 

如果你想获取相同的“随机”的元素,您可以修复种子:

data.takeSample(false, 1, seed = 10L) 
// res14: Array[Int] = Array(62) 

data.takeSample(false, 1, seed = 10L) 
// res15: Array[Int] = Array(62) 
+0

我们可以将System.nanoTime.toInt作为种子吗? –

+0

你可以使用任何你喜欢的种子。然而种子很长,所以你应该给它一个。我不知道为什么@eliasah使用随机种子,因为它是[默认值](https://spark.apache.org/docs/1.5.2/api/scala/index.html#org.apache.spark .rdd.RDD)。 –

+0

这是真的@mlk我不确定,因为我在飞行中编写代码。 – eliasah