第三章_Hive 数据类型
1. 基本类型
tinyint
smalint
int
bigint
boolean
float
double
decimal
string : 相当于varchar,可变字符串,不用指定长度,理论上可以存储2GB字符数
timestamp
binary
2. 集合数据类型
struct
map
array
案例1 : array 类型

-- array类型 案例
create table arraytab
(
name string,
friends array<string>
)
row format delimited fields terminated by '#' -- 列分隔符
collection items terminated by ',' -- 集合(array、struct、map) 元素分隔符
lines terminated by '\n' -- 行分割符
;
-- 数据
刘备#关羽,张飞,马超,诸葛亮,黄忠,赵云
曹操#许褚,荀彧,司马懿
-- 从本地导入数据到hive
load data local inpath '/root/sanguo.txt' overwrite into table home.arraytab;
-- 查询数据
select name
, friends[0]
, friends[1]
, friends[2]
, friends[3]
, friends[4]
, friends[5]
from home.arraytab;
-- 结果
name _c1 _c2 _c3 _c4 _c5 _c6
刘备1 关羽 张飞 马超 诸葛亮 黄忠 赵云
曹操1 许褚 荀彧 司马懿 NULL NULL NULL
案例2 : struct 类型

-- struct 类型
create table structtab
(
name string,
friend struct<name:string, age:int, address:string>
)
row format delimited fields terminated by '#' -- 列分隔符
collection items terminated by ',' -- 集合(array、struct、map) 元素分隔符
lines terminated by '\n' -- 行分割符
;
-- 数据
刘备#关羽,120,山西
曹操#许褚,20
孙权#吕蒙,30,杭州,100
-- 从本地导入数据到hive
load data local inpath '/root/sanguo1.txt' overwrite into table home.structtab;
-- 查询数据
select name
, friend
, friend.name
, friend.age
, friend.address
from home.structtab;
-- 结果
name friend name age address
刘备 {"name":"关羽","age":120,"address":"山西"} 关羽 120 山西
曹操 {"name":"许褚","age":20,"address":null} 许褚 20 NULL
孙权 {"name":"吕蒙","age":30,"address":"杭州"} 吕蒙 30 杭州
案例3 : map 类型

--案例3 : map 类型
create table maptab
(
name string,
friend map<string, int>
)
row format delimited fields terminated by '#' -- 列分隔符
collection items terminated by ',' -- 集合(array、struct、map 元素分隔符)
map keys terminated by ':' -- map 的 key、value 分隔符
lines terminated by '\n' -- 行分割符
;
-- 数据
刘备#关羽:120,张飞:20
曹操#许褚:20
孙权#吕蒙:30:杭州:100
-- 从本地导入数据到hive
load data local inpath '/root/sanguo2.txt' overwrite into table home.maptab;
-- 查询数据
select name
,friend
,friend['关羽']
,friend['山西']
from home.maptab;
-- 结果
name friend _c2 _c3
刘备 {"关羽":120,"山西":null} 120 NULL
曹操 {"许褚":20} NULL NULL
孙权 {"吕蒙":null} NULL NULL
3. 类型转换
1. 隐式类型转换(自动类型转换) 规则
1. 小类型 自动转向 大类型
tinyint 转 int
int 转 bigint
2. 所有的 整数类型、float、string 都可以自动转换 double类型
3. tinyint、smallint、int都 可以自动转换成 float
4. boolean 不可以转换成 其他任何类型
2. 强制类型转换
1. cast('10' as int)
如果强制类型转换失败,将返回null