Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten list inside RDD?

Is it possible to flatten list inside RDD? For example convert:

 val xxx: org.apache.spark.rdd.RDD[List[Foo]]

to:

 val yyy: org.apache.spark.rdd.RDD[Foo]

How to do this?

like image 478
zork Avatar asked Jan 30 '15 10:01

zork


2 Answers

val rdd = sc.parallelize(Array(List(1,2,3), List(4,5,6), List(7,8,9), List(10, 11, 12)))
// org.apache.spark.rdd.RDD[List[Int]] = ParallelCollectionRDD ...

val rddi = rdd.flatMap(list => list)
// rddi: org.apache.spark.rdd.RDD[Int] = FlatMappedRDD ...

// which is same as rdd.flatMap(identity)
// identity is a method defined in Predef object.
//    def identity[A](x: A): A

rddi.collect()
// res2: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
like image 77
Shyamendra Solanki Avatar answered Nov 20 '22 18:11

Shyamendra Solanki


You just need to flatten it, but as there's no explicit 'flatten' method on RDD, you can do this:

rdd.flatMap(identity)
like image 35
maasg Avatar answered Nov 20 '22 17:11

maasg