标签:UDTF

共 1 篇相关文章

IT 累计浏览 6,227

HIVE中UDTF编写和使用

UDTF(User-Defined Table-Generating Functions)用于解决输入一行输出多行(One-to-many mapping)的需求。编写自定义 UDTF 时,需继承 org.apache.hadoop.hive.ql.udf.generic.GenericUDTF,并实现 initialize、process、close 三个方法:initialize 返回输出行的信息(返回个数、类型),process 处理传入参数并通过 forward() 返回结果,close 负责资源清理。文中以 ExplodeMap 为例,演示了将 "key:value;key:value;" 格式字符串切分为 key、value 两列的完整实现,包括参数校验和 StructObjectInspector 的构造。

使用上 UDTF 有两种方式:一是直接放在 select 后面,如 select explode_map(properties) as (col1,col2) from src,此时不能添加其他字段、不能嵌套调用、也不能与 group by/cluster by/distribute by/sort by 一起使用;二是与 lateral view 配合使用,如 select src.id, mytable.col1, mytable.col2 from src lateral view explode_map(properties) mytable as col1, col2,这种方式更便于日常使用,其执行过程相当于分别抽取后再 union 到一张表中。