如何取消嵌套带有键的数组以便之后加入?
How to unnest array with keys to join on afterwards?
我有两个表,分别是table1
和table2
。 table1
大,而 table2
小。另外,我有一个 UDF 函数,其接口定义如下:
--table1--
id
1
2
3
--table2--
category
a
b
c
d
e
f
g
UDF: foo(id: Int): List[String]
我打算先调用UDF得到对应的类别:foo(table1.id)
,这会return一个WrappedArray,然后我想加入每个category
in table2
做更多的操作。预期结果应如下所示:
--view--
id,category
1,a
1,c
1,d
2,b
2,c
3,e
3,f
3,g
我试图在 Hive 中找到一个 unnest 方法,但没有运气,有人可以帮助我吗?谢谢!
我相信你想使用 explode
function or Dataset's flatMap
operator.
explode
函数为给定数组或映射列中的每个元素创建一个新行。
flatMap
运算符 returns 一个新的数据集,方法是首先将函数应用于该数据集的所有元素,然后展平结果。
执行 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
应该很容易了。
我有两个表,分别是table1
和table2
。 table1
大,而 table2
小。另外,我有一个 UDF 函数,其接口定义如下:
--table1--
id
1
2
3
--table2--
category
a
b
c
d
e
f
g
UDF: foo(id: Int): List[String]
我打算先调用UDF得到对应的类别:foo(table1.id)
,这会return一个WrappedArray,然后我想加入每个category
in table2
做更多的操作。预期结果应如下所示:
--view--
id,category
1,a
1,c
1,d
2,b
2,c
3,e
3,f
3,g
我试图在 Hive 中找到一个 unnest 方法,但没有运气,有人可以帮助我吗?谢谢!
我相信你想使用 explode
function or Dataset's flatMap
operator.
explode
函数为给定数组或映射列中的每个元素创建一个新行。
flatMap
运算符 returns 一个新的数据集,方法是首先将函数应用于该数据集的所有元素,然后展平结果。
执行 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
应该很容易了。