【发布时间】:2020-01-24 18:35:24
【问题描述】:
我正在尝试使用 UDF 根据我定义的自定义排序对结构数组进行排序。
这是我希望获得的结果类型的示例:
input_tbl
+-------+-------+------+
| id1 | id2 | num |
+-------+-------+------+
| 1 | 2 | 1 |
| 1 | 3 | -3 |
| 1 | 4 | 2 |
+-------+-------+------+
output_tbl
+-------+-------+------+
| id1 | id2 | num |
+-------+-------+------+
| 1 | 3 | -3 |
+-------+-------+------+
案例类和UDF的一些示例代码如下所示。
case class Score(id: String, num: Int) extends Ordered[Score] {
def compare(that: Score): Int = {
abs(this.num-that.num)
}
}
val toScoreType : UserDefinedFunction = udf((id: String, num: Int) => {
Score(id, num)
})
val sortScoreList: UserDefinedFunction = udf((score_list: Array[Score]) => {
score_list.sorted
})
我将 sortScore UDF 调用如下:
val temp = input_tbl
.select('id1, toScoreType('id2, 'num).as("score"))
.groupBy('id1)
.agg((collect_set('score)).as("score_list"))
temp.select('id1, sortScoreList('score_list).as("result"))
但是,我收到“java.lang.ClassCastException: scala.collection.mutable.WrappedArray$ofRef”错误。
有人对可能导致问题的原因有任何想法吗?
【问题讨论】:
标签: scala sorting apache-spark user-defined-functions