Hive中的数据类型
在hive中的数据类型
①:int bigint double string timestamp
②:struct 类似于java对象 pojo类
③:array 数组
④:map 键值对
实例步骤
1. 准备数据
benben,fengjie_furong,xiaoben:18_daben:19,hui long guan_beijing
yangyang,caicai_susu,xiao yang:18_xiaoxiao yang:19,chao yang_beijing
2. 建表
create table tb_user(
name string , --string
friends array<string> ,--数组
children map<string ,int> ,--集合
address struct<street:string , city:string> --结构体
)
row format delimited fields terminated by ',' --字段之间用逗号切割
collection items terminated by '_' --集合元素之间用"_"切割
map keys terminated by ':'--key,value之间的切割符
lines terminated by '\n';--行之间的切割符
load data local inpath "/opt/data/collection.txt" into table tb_user ; --导入数据
3. 对表中的数据进行处理
①:数组
1)取值 array[index]
2 ) 长度 size(array)
select friends[0] fs1 ,friends[1] fs2 from tb_user;--根据索引取值
select friends[if (1>size(friends) ,0,1)] from tb_user;
②:map集合
1)取值 通过key获取map的value值
select children['daben'] from tb_user;
2)获取map集合中的所有key map_keys(map) | map_values(map)
select map_keys(children) from tb_user;
3)获取map集合的长度 size(map)
select size(children) from tb_user;
4)行转列
select name,child,age
from tb_user
lateral view explode(children) t
as child,age;
③:结构体
结构体获取属性
select address.street,address.city from tb_user;
功能扩展一:使用反射reflect 函数调用java类的方法
reflect(class , methodName , args…) --class:类的全路径,方法名 参数
1 编写java程序
2 打包
3 上传到linux系统
4 add jar /test.jar 将jar包添加到 $HIVE_HOME/lib/目录下
5 select reflect(‘cn._51doit.test.Test1’ , ‘test1’ , ‘HELLO’ , 23) ;
功能扩展二:用户自定义函数
自定义函数
1 创建maven工程
2 编写 类 继承 UDF 类
3 重写方法 evaluate 允许重载
4 打包上传的HDFS
5 创建函数
create function sayHello as 'com._51doit.functions.MyFunction' using jar 'hdfs://linux01:8020/func.jar' ;
select sayHello('abc') ; hello abc
select sayHello('abc',2) ; hello abc20