深入浅出学Hive——Hive高级编程,
目录:
初始Hive
Hive安装与配置
Hive内建操作符与函数开发
Hive JDBC
Hive参数
Hive高级编程
Hive QL
Hive Shell基本操作
Hive优化
Hive体系结构
Hive原理
SELECT my_add (8,9.1) FROM scores; •结果是17.1,UDF将类型为Int的参数转化成double。类型的饮食转换是通过UDFResolver来进行控制的 第三部分:UDAF UDAF •Hive查询数据时,有些聚类函数在HQL没有自带,需要用户自定义实现 •用户自定义聚合函数: Sum, Average…… n – 1 •UDAF(User- Defined Aggregation Funcation) 用法 •一下两个包是必须的import org.apache.hadoop.hive.ql.exec.UDAF和 org.apache.hadoop.hive.ql.exec.UDAFEvaluator 开发步骤 •函数类需要继承UDAF类,内部类Evaluator实UDAFEvaluator接口 •Evaluator需要实现 init、iterate、terminatePartial、merge、terminate这几个函数 a)init函数实现接口UDAFEvaluator的init函数。 b)iterate接收传入的参数,并进行内部的轮转。其返回类型为boolean。 c)terminatePartial无参数,其为iterate函数轮转结束后,返回轮转数据,terminatePartial类似于hadoop的Combiner。 d)merge接收terminatePartial的返回结果,进行数据merge操作,其返回类型为boolean。 e)terminate返回最终的聚集函数结果。 执行步骤 •执行求平均数函数的步骤 a)将java文件编译成Avg_test.jar。 b)进入hive客户端添加jar包: hive>add jar /run/jar/Avg_test.jar。 c)创建临时函数: hive>create temporary function avg_test 'hive.udaf.Avg'; d)查询语句: hive>select avg_test(scores.math) from scores; e)销毁临时函数: hive>drop temporary function avg_test; UDAF代码示例 public class MyAvg extends UDAF { public static class AvgEvaluator implements UDAFEvaluator { } public void init() {} public boolean iterate(Double o) {} public AvgState terminatePartial() {} public boolean terminatePartial(Double o) { } public Double terminate() {} } 第四部分:UDTF UDTF •UDTF(User-Defined Table-Generating Functions) 用来解决 输入一行输出多行(On-to-many maping) 的需求。 开发步骤 •UDTF步骤: •必须继承org.apache.Hadoop.hive.ql.udf.generic.GenericUDTF •实现initialize, process, close三个方法 •UDTF首先会 •调用initialize方法,此方法返回UDTF的返回行的信息(返回个数,类型)
初始化完成后,会调用process方法,对传入的参数进行处理,可以通过forword()方法把结果返回 •最后close()方法调用,对需要清理的方法进行清理 使用方法 •UDTF有两种使用方法,一种直接放到select后面,一种和lateral view一起使用 •直接select中使用:select explode_map(properties) as (col1,col2) from src; •不可以添加其他字段使用:select a, explode_map(properties) as (col1,col2) from src •不可以嵌套调用:select explode_map(explode_map(properties)) from src •不可以和group by/cluster by/distribute by/sort by一起使用:select explode_map(properties) as (col1,col2) from src group by col1, col2 •和lateral view一起使用:select src.id, mytable.col1, mytable.col2 from src lateral view explode_map(properties) mytable as col1, col2; 此方法更为方便日常使用。执行过程相当于单独执行了两次抽取,然后union到一个表里。 lateral view • Lateral View语法 •lateralView: LATERAL VIEW udtf(expression) tableAlias AS columnAlias (',' columnAlias)* fromClause: FROM baseTable (lateralView)* •Lateral View用于UDTF(user-defined table generating functions)中将行转成列,例如explode(). •目前Lateral View不支持有上而下的优化。如果使用Where子句,查询可能将不被编译。解决方法见: 此时,在查询之前执行set hive.optimize.ppd=false; • 例子 •pageAds。它有两个列
| string pageid | Array<int> adid_list |
| " front_page" | [1, 2, 3] |
| "contact_page " | [ 3, 4, 5] |
本站文章为和通数据库网友分享或者投稿,欢迎任何形式的转载,但请务必注明出处.
同时文章内容如有侵犯了您的权益,请联系QQ:970679559,我们会在尽快处理。