hive UDF详解&实例
来源:互联网 发布:林若宁 知乎 编辑:程序博客网 时间:2024/06/01 10:05
UDF可以直接应用于select语句,对查询结果做格式化处理后输出内容
操作作用于单个数据行,且产生了一个数据行作为输出
实现UDF(User-Defined-Function)
需要继承org.apache.hadoop.hive.ql.UDF
需要实现evaluate函数(evaluate函数支持重载)
实例:
实现UDF查找hive表中array类型列的值中是否包含某一项
SELECT FIND_IN_ARRAY(column, ‘key’) FROM users;
数据准备
# cat /root/person.txt zhangsan beijing,shanghai,tianjin,hangzhoulisi changchu,chengdu,wuhan
创建表&导入数据
Create table users(name string, worklocations array<string> ) row format delimited fields terminated by '\t' collection items terminated by ','; load data local inpath '/root/person.txt ' OVERWRITE INTO TABLE users;
hive array基本操作看这里建表+查询+修改
关键代码
public class find_in_array extends UDF{ public ArrayList<String> evaluate(String keywords,ArrayList<String> column){ //参数类型使用arraylist<String>对应hive中的array<string>,而不是String[] if(column.contains(keywords)){ return column; }else{ return null; } } public String evaluate(String keywords,ArrayList<String> column,String name){ //重载evaluate,另一种查询方式,返回name值 if(column.contains(keywords)){ return name; }else{ return null; } }}
编写完成后,导出jar包
UDF使用方法:
方法1
会话结束后,函数会自动销毁,所以每次打开新的会话,都要重新add jar并create temporary function
hive> add jar /root/find_in_array.jar;Added [/root/find_in_array.jar] to class pathAdded resources: [/root/find_in_array.jar]hive> create temporary function find_in_array as 'com.neu.hive.UDF.find_in_array';OKTime taken: 0.448 secondshive> select find_in_array('beijing',worklocations,name)from users;OKzhangsanNULLTime taken: 0.578 seconds, Fetched: 2 row(s)hive> select find_in_array('beijing',worklocations)from users;OK["beijing","shanghai","tianjin","hangzhou"]NULLTime taken: 0.049 seconds, Fetched: 2 row(s)
方法2
使用hive -i参数在进入hive时自动初始化,会话结束后,函数也会自动销毁
# cat hive_init add jar /root/find_in_array.jar;create temporary function topK as 'com.neu.hive.UDF.find_in_array';# hive -i hive_init
方法3
将UDF注册为内置函数,如果不是特别通用,固化下来的函数,不要使用这种方法
运行结果
常见错误
报以下错误,一定要有evaluate函数,且参数要匹配,要仔细检查!
hive> select find(name,users.worklocations)from users;
FAILED: SemanticException [Error 10014]: Line 1:7 Wrong arguments ‘worklocations’: No matching method for class com.neu.hive.UDF.find_in_array with (string, array). Possible choices:
1 0
- hive UDF详解&实例
- hive UDF开发实例
- hive-udf开发实例1
- hive udf,udaf,udtf详解
- linux中用eclipse开发Hadoop mapreduce与Hive UDF实例详解及其配置说明
- Hive 用户自定义函数UDF详解
- hive中UDF、UDAF和UDTF详解
- Hive 混合函数 UDTF UDF UDAF详解
- hive udf
- hive-udf
- hive UDF
- hive UDF
- hive UDF
- hive udf
- hive udf
- Hive UDF
- HIVE UDF
- hive udf
- Kubernetes简介
- WinHttp之获取网站首页源码
- Android Jni 注册方法。以及在eclipse作为第三方so的使用
- Maven+Postgresql+SpringMVC+MyBatis+AngularJS+Bootstrap环境搭建
- 中介者模式 [Mediator Pattern]
- hive UDF详解&实例
- NYOJ38布线问题_最小生成树
- [译]榨取SQLite性能:插入
- 关于Android 签名
- 我必须得告诉大家的MySQL优化原理
- mybatis中refid是什么意思
- SpringBoot非官方教程 | 第二十二篇: 创建含有多module的springboot工程
- 解析存储过程中常见变量
- Failed to execute goal org.apache.maven.plugins:maven-deploy-plugin:2.7:deploy (default-deploy) on p