I have a quite a big dataset (100 million+ records with 100's of columns) that I am processing with spark. I am reading the data into a spark dataset and I want to filter this dataset and map a subset of its fields to a case class.
the code looks somewhat similar,
case class Subset(name:String,age:Int)
case class Complete(name:String,field1:String,field2....,age:Int)
val ds = spark.read.format("csv").load("data.csv").as[Complete]
#approach 1
ds.filter(x=>x.age>25).map(x=> Subset(x.name,x.age))
#approach 2
ds.flatMap(x=>if(x.age>25) Seq(Subset(x.name,x.age)) else Seq.empty)
Which approach is better? Any additional hints on how I can make this code more performant?
Thanks!
Edit
I ran some tests to compare the runtimes and it looks like approach 2 is quite faster, the code i used for getting the runtimes is as follows,
val subset = spark.time {
ds.filter(x=>x.age>25).map(x=> Subset(x.name,x.age))
}
spark.time {
subset.count()
}
and
val subset2 = spark.time {
ds.flatMap(x=>if(x.age>25) Seq(Subset(x.name,x.age)) else Seq.empty)
}
spark.time {
subset2.count()
}