首页 > 解决方案 > Spark Dataframe - 获取所有对列表(Scala)

问题描述

我有以下情况:我有一个以“数组”作为架构的数据框。现在我想为每个数组获取所有对列表并将其再次保存在数据框中。例如:

这是原始数据框:

+---------------+
|  candidateList|
+---------------+
|         [1, 2]|
|      [2, 3, 4]|
|      [1, 3, 5]|
|[1, 2, 3, 4, 5]|
|[1, 2, 3, 4, 5]|
+---------------+

这就是计算后的样子:

+---------------+
|  candidates   |
+---------------+
|         [1, 2]|
|         [2, 3]|
|         [2, 4]|
|         [3, 4]|
|         [1, 3]|
|         [1, 5]|
|         [3, 5]|
|and so on...   |
+---------------+

我真的不知道这在火花中是如何实现的,也许有人给我一个小费。

亲切的问候

标签: scalaapache-sparkapache-spark-sql

解决方案


您需要创建一个 UDF(用户定义函数)并将其与explode函数一起使用。由于 Scala 集合的combinations方法,UDF 本身很简单:

import scala.collection.mutable
import org.apache.spark.sql.functions._
import spark.implicits._

val pairsUdf = udf((arr: mutable.Seq[Int]) => arr.combinations(2).toArray)
val result = df.select(explode(pairsUdf($"candidateList")) as "candidates")

result.show(numRows = 8)
// +----------+
// |candidates|
// +----------+
// |    [1, 2]|
// |    [2, 3]|
// |    [2, 4]|
// |    [3, 4]|
// |    [1, 3]|
// |    [1, 5]|
// |    [3, 5]|
// |    [1, 2]|
// +----------+

推荐阅读