前言
关系数据库里有表(table),分区,hive里也有这些东西,这些东西在hive技术里称为hive的数据模型
Hive支持两种数据类型,一类叫原子数据类型,一类叫复杂数据类型。
原子数据类型包括数值型、布尔型和字符串类型,具体如下表所示:
原子数据
复杂数据
复杂数据类型包括数组(ARRAY)、映射(MAP)和结构体(STRUCT),具体如下表所示:
基本类型转换的转换包含关系
案例实操
1) 假设某表有如下一行,我们用JSON格式来表示其数据结构。在Hive下访问的格式为
{
"name": "xiongxiong",
"friends": ["huahua" , "lili"] , //列表Array,
"children": { //键值Map,
"xiao xiong": 18 ,
"xiaoxiao xiong": 19
}
"address": { //结构Struct,
"street": "hui long guan" ,
"city": "beijing"
}
}
2)基于上述数据结构,我们在Hive里创建对应的表,并导入数据。
创建本地测试文件test.txt
xiongxiong,huahua_lili,xiao xiong:18_xiaoxiao xiong:19,hui long guan_beijing
yangyang,caicai_susu,xiao yang:18_xiaoxiao yang:19,chao yang_beijing
注意:MAP,STRUCT和ARRAY里的元素间关系都可以用同一个字符表示,这里用“_”。
3)Hive上创建测试表test
create table test(
name 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 ':'
lines terminated by '\n';
字段解释:row format delimited fields terminated by ','
– 列分隔符
collection items terminated by '_'
--MAP STRUCT 和 ARRAY 的分隔符(数据分割符号)
map keys terminated by ':'
-- MAP中的key与value的分隔符
lines terminated by ‘\n’; – 行分隔符
4)导入文本数据到测试表
hive (default)> load data local inpath '/opt/module/datas/test.txt'into table test;
5)访问三种集合列里的数据,以下分别是ARRAY,MAP,STRUCT的访问方式
hive (default)> select friends[1],children['xiao xiong'],address.city from test
where name="xiongxiong";
hive类型转换
官网上有(更新)
镶套转换
SELECT (cast(cast(a as string) as double)) from users;;
hive中 日期格式转化办法:
2014-11-10 和 20141110相互转化的办法:
1.from_unixtime && unix_timestamp
– 20141110
select from_unixtime(unix_timestamp(‘2014-11-10’,‘yyyy-mm-dd’),‘yyyymmdd’) from default.dual;
– 2014-11-10
select from_unixtime(unix_timestamp(‘20141110’,‘yyyymmdd’),‘yyyy-mm-dd’) from default.dual;
2.substr + concat
– 20141110
select concat(substr(‘2014-11-10’,1,4),substr(‘2014-11-10’,6,2),substr(‘2014-11-10’,9,2)) from default.dual;
– 2014-11-10
select concat(substr(‘20141110’,1,4),’-’,substr(‘20141110’,5,2),’-’,substr(‘20141110’,7,2)) from default.dual;
附加:hive 获取当前时间
select from_unixtime(unix_timestamp(),‘yyyy-MM-dd HH:mm:ss’) from default.dual;