我有一个Spark DataFrame,其中我的一列是对象数组。我想做一个过滤该数组的操作。在下面的示例中,我有一个有孩子的父母,我只想让成年孩子。
import spark.implicits._
case class Child(name: String, age: Int)
case class Parent(name: String, children: Array[Child])
val rawData = Seq(Parent("Mom", Array(Child("Jane", 9))), Parent("Dad", Array(Child("Hubert", 28), Child("David", 27), Child("Jim", 25))))
val data = spark.createDataFrame(rawData)
我能找到的最接近的是:
val adultChildren = udf((children: mutable.WrappedArray[Child]) => {
val rowArray = children.asInstanceOf[mutable.WrappedArray[GenericRowWithSchema]]
val ret = rowArray.filter(c => c.getAs[Int]("age") > 18)
ret.asInstanceOf[mutable.WrappedArray[Child]]
})
data.select(adultChildren($"children")).show()
这有点烦人。我猜它的优点是Spark花更少的时间(反序列化对象),但是它很冗长。
有没有更简洁的方法可以做到这一点?
如果您可以使用数据集,那么它将变得非常简单:
data.map(_.children.filter(_.age > 18).toList)
但是,如果您不拘泥于DataFrames:
data.select($"name", explode($"children").as("child"))
.where($"child.age" > 18)
.groupBy($"name").agg(collect_list($"child"))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句