与 Hive UDF/UDAF/UDTF 集成

描述

Spark SQL 支持集成 Hive UDF、UDAF 和 UDTF。与 Spark UDF 和 UDAF 类似,Hive UDF 以单行作为输入并生成单行作为输出,而 Hive UDAF 对多行进行操作并返回单行聚合结果。此外,Hive 还支持 UDTF(用户定义的表函数),它们以一行作为输入并返回多行作为输出。要使用 Hive UDF/UDAF/UTF,用户应在 Spark 中注册它们,然后在 Spark SQL 查询中使用它们。

示例

Hive 有两个 UDF 接口:UDFGenericUDF。以下示例使用从 GenericUDF 派生的 GenericUDFAbs

-- Register `GenericUDFAbs` and use it in Spark SQL.
-- Note that, if you use your own programmed one, you need to add a JAR containing it
-- into a classpath,
-- e.g., ADD JAR yourHiveUDF.jar;
CREATE TEMPORARY FUNCTION testUDF AS 'org.apache.hadoop.hive.ql.udf.generic.GenericUDFAbs';

SELECT * FROM t;
+-----+
|value|
+-----+
| -1.0|
|  2.0|
| -3.0|
+-----+

SELECT testUDF(value) FROM t;
+--------------+
|testUDF(value)|
+--------------+
|           1.0|
|           2.0|
|           3.0|
+--------------+

-- Register `UDFSubstr` and use it in Spark SQL.
-- Note that, it can achieve better performance if the return types and method parameters use Java primitives.
-- e.g., UDFSubstr. The data processing method is UTF8String <-> Text <-> String. we can avoid UTF8String <-> Text. 
CREATE TEMPORARY FUNCTION hive_substr AS 'org.apache.hadoop.hive.ql.udf.UDFSubstr';

select hive_substr('Spark SQL', 1, 5) as value;
+-----+
|value|
+-----+
|Spark|
+-----+

以下示例使用从 GenericUDTF 派生的 GenericUDTFExplode

-- Register `GenericUDTFExplode` and use it in Spark SQL
CREATE TEMPORARY FUNCTION hiveUDTF
    AS 'org.apache.hadoop.hive.ql.udf.generic.GenericUDTFExplode';

SELECT * FROM t;
+------+
| value|
+------+
|[1, 2]|
|[3, 4]|
+------+

SELECT hiveUDTF(value) FROM t;
+---+
|col|
+---+
|  1|
|  2|
|  3|
|  4|
+---+

Hive 有两个 UDAF 接口:UDAFGenericUDAFResolver。以下示例使用从 GenericUDAFResolver 派生的 GenericUDAFSum

-- Register `GenericUDAFSum` and use it in Spark SQL
CREATE TEMPORARY FUNCTION hiveUDAF
    AS 'org.apache.hadoop.hive.ql.udf.generic.GenericUDAFSum';

SELECT * FROM t;
+---+-----+
|key|value|
+---+-----+
|  a|    1|
|  a|    2|
|  b|    3|
+---+-----+

SELECT key, hiveUDAF(value) FROM t GROUP BY key;
+---+---------------+
|key|hiveUDAF(value)|
+---+---------------+
|  b|              3|
|  a|              3|
+---+---------------+