我有两张表,即table1
和 table2
. table1
很大,而 table2
是小。另外,我有一个 UDF 函数,其接口(interface)定义如下:
--table1--
id
1
2
3
--table2--
category
a
b
c
d
e
f
g
UDF: foo(id: Int): List[String]
我打算先调用UDF获取对应的分类:
foo(table1.id)
,它将返回一个 WrappedArray,然后我想加入每个 category
在 table2
做一些更多的操作。预期结果应如下所示:--view--
id,category
1,a
1,c
1,d
2,b
2,c
3,e
3,f
3,g
我试图在 Hive 中找到一种 unnest 方法,但没有运气,有人可以帮我吗?谢谢!
最佳答案
相信你想用explode
function或数据集的 flatMap
operator .explode
函数为给定数组或映射列中的每个元素创建一个新行。flatMap
运算符首先将一个函数应用于此数据集的所有元素,然后将结果展平,从而返回一个新的数据集。
执行 UDF 后 foo(id: Int): List[String]
你最终会得到一个 Dataset
类型为 array
的列.
val fooUDF = udf { id: Int => ('a' to ('a'.toInt + id).toChar).map(_.toString) }
// table1 with fooUDF applied
val table1 = spark.range(3).withColumn("foo", fooUDF('id))
scala> table1.show
+---+---------+
| id| foo|
+---+---------+
| 0| [a]|
| 1| [a, b]|
| 2|[a, b, c]|
+---+---------+
scala> table1.printSchema
root
|-- id: long (nullable = false)
|-- foo: array (nullable = true)
| |-- element: string (containsNull = true)
scala> table1.withColumn("fooExploded", explode($"foo")).show
+---+---------+-----------+
| id| foo|fooExploded|
+---+---------+-----------+
| 0| [a]| a|
| 1| [a, b]| a|
| 1| [a, b]| b|
| 2|[a, b, c]| a|
| 2|[a, b, c]| b|
| 2|[a, b, c]| c|
+---+---------+-----------+
有了这个,
join
应该很容易。
关于apache-spark - 之后如何使用键取消嵌套数组以加入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43411832/