KAs*_*KAs 4 hive hiveql apache-spark apache-spark-sql
我有两张桌子,即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]
Run Code Online (Sandbox Code Playgroud)
我打算首先调用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
Run Code Online (Sandbox Code Playgroud)
我试图在Hive中找到一个不需要的方法,但没有运气,有人可以帮助我吗?谢谢!
我相信你想使用explode 函数或数据集的flatMap 运算符.
explode 函数为给定数组或映射列中的每个元素创建一个新行.
flatMap operator通过首先将函数应用于此数据集的所有元素,然后展平结果来返回新的数据集.
执行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|
+---+---------+-----------+
Run Code Online (Sandbox Code Playgroud)
有了它,join应该很容易.
| 归档时间: |
|
| 查看次数: |
2883 次 |
| 最近记录: |