Reputation: 59
I have a dataframe with a column having Array:
+----------------------------+
|User | Color |
+----------------------------+
|User1 | [Green,Blue,Red] |
|User2 | [Blue,Red] |
+----------------------------+
I am trying to filter for User1
and get the list of colors into a Scala List:
val colorsList: List[String] = List("Green","Blue","Red")
Here's what I have tried so far (output is added as comments):
Attempt 1:
val dfTest1 = myDataframe.where("User=='User1'").select("Color").rdd.map(r => r(0)).collect()
println(dfTest1) //[Ljava.lang.Object;@44022255
for(EachColor<- dfTest1){
println(EachColor) //WrappedArray(Green, Blue, Red)
}
Attempt 2:
val dfTest2 = myDataframe.where("User=='User1'").select("Color").collectAsList.get(0).getList(0)
println(dfTest2) //[Green, Blue, Red] but type is util.List[Nothing]
Attempt 3:
val dfTest32 = myDataframe.where("User=='User1'").select("Color").rdd.map(r => r(0)).collect.toList
println(dfTest32) //List(WrappedArray(Green, Blue, Red))
for(EachColor <- dfTest32){
println(EachColor) //WrappedArray(Green, Blue, Red)
}
Attempt 4:
val dfTest31 = myDataframe.where("User=='User1'").select("Color").map(r => r.getString(0)).collect.toList
//Exception : scala.collection.mutable.WrappedArray$ofRef cannot be cast to java.lang.String
Upvotes: 2
Views: 437
Reputation: 42352
You can try getting as Seq[String]
and converting toList
:
val colorsList = df.where("User=='User1'")
.select("Color")
.rdd.map(r => r.getAs[Seq[String]](0))
.collect()(0)
.toList
Or equivalently
val colorsList = df.where("User=='User1'")
.select("Color")
.collect()(0)
.getAs[Seq[String]](0)
.toList
Upvotes: 2