Hive是一种构建在Hadoop上的数据仓库,Hive把SQL查询转换为一些列在Hadoop集群上运行的MapReduce做业,是MapReduce更高层次的抽象,不用编写具体的MapReduce方法。Hive将数据组织为表,这就使得HDFS上的数据有告终构,元数据即表的模式,都存储在名为metastore的数据库中。java
Hive能够容许用户编写本身定义的函数UDF,在查询中使用。Hive中有3中UDF:数据库
UDF:操做单个数据行,产生单个数据行。apache
UDAF:操做多个数据行,产生一个数据行。vim
UDTF:操做一个数据行,产生多个数据行。服务器
用户构建UDF使用过程以下:svn
第一步:继承UDF,实现evaluate()方法,方法的参数和返回类型本身定义。函数
第二步:将写好的类打包成jar文件,如myhive.jar。oop
第三步:进入到Hive终端,利用add jar path/myhive.jar将自定义的jar加入到Hive环境中。lua
第四步:为该类起一个别名,create temporary function toUpper as 'com.lixue.udf.UDFToUpper'。spa
第五步:在select语句中使用toUpper()方法。
示例:
/** * 自定义UDF将小写字母转换成大写字母 * @author 廖*民 * time : 2015年1月30日下午8:18:59 * @version */ public class UDFToUpper extends UDF { /** * evaluate方法的返回类型和参数都是自定义的 * 另外evaluate方法还支持重载。 * @param s * @return */ public Text evaluate(final Text s) { if (null == s) { return null; } //返回大写字母 return new Text(s.toString().toUpperCase()); } }
#添加到Hive环境:
hive (hive)> add jar /usr/local/src/udfToUpper.jar; Added /usr/local/src/udfToUpper.jar to class path Added resource: /usr/local/src/udfToUpper.jar hive (hive)>
#建立临时函数:
hive (hive)> create temporary function toUpper as 'com.lixue.udf.UDFToUpper'; OK Time taken: 0.01 seconds hive (hive)>
hive (hive)> select * from employees; OK name salary subordinate deductions address date_time type lavimer 15000.0 ["li","lu","wang"] {"k1":1.0,"k2":2.0,"k3":3.0} {"street":"dingnan","city":"ganzhou","num":101} 2015-01-24 love liao 18000.0 ["liu","li","huang"] {"k4":2.0,"k5":3.0,"k6":6.0} {"street":"dingnan","city":"ganzhou","num":102} 2015-01-24 love zhang 19000.0 ["xiao","wen","tian"] {"k7":7.0,"k8":8.0,"k8":8.0} {"street":"dingnan","city":"ganzhou","num":103} 2015-01-24 love Time taken: 0.914 seconds hive (hive)>
hive (hive)> select * from employees; //MapReduce... OK name _c1 lavimer LAVIMER liao LIAO zhang ZHANG Time taken: 4.674 seconds hive (hive)>
hive (hive)> drop temporary function toUpper; OK Time taken: 0.017 seconds hive (hive)> select toUpper(name) from employees; FAILED: Error in semantic analysis: Line 1:7 Invalid function 'toUpper' hive (hive)>
更多UDF实例请参考:https://svn.apache.org/repos/asf/hive/tags/release-0.8.1/ql/src/java/org/apache/hadoop/hive/ql/udf/