文章目录
一、简单数据类型
- 一、简单数据类型
- 1.1、类型转换
- 1.1.1、隐式类型转换规则如下
- 1.1.2、可以使用CAST操作显示进行数据类型转换
- 二、复杂数据类型
- 2.1、三种复杂类型的创建,及数据导入,查询
Hive的原子数据类型是可以进行隐式转换的,类似于Java的类型转换,例如某表达式使用INT类型,TINYINT会自动转换为INT类型,但是Hive不会进行反向转化,例如,某表达式使用TINYINT类型,INT不会自动转换为TINYINT类型,它会返回错误,除非使用CAST操作。
1.1.1、隐式类型转换规则如下- (1)任何整数类型都可以隐式地转换为一个范围更广的类型,如TINYINT可以转换成INT,INT可以转换成BIGINT。
- (2)所有整数类型、FLOAT和STRING类型都可以隐式地转换成DOUBLE。
- (3)TINYINT、SMALLINT、INT都可以转换为FLOAT。
- (4)BOOLEAN类型不可以转换为任何其它的类型。
例如CAST(‘1’ AS INT)将把字符串’1’ 转换成整数1;如果强制类型转换失败,如执行CAST(‘X’ AS INT),表达式返回空值 NULL。
二、复杂数据类型 Hive有三种复杂数据类型ARRAY、MAP 和 STRUCT。ARRAY和MAP与Java中的Array和Map类似,而STRUCT与C语言中的Struct类似,它封装了一个命名字段集合,复杂数据类型允许任意层次的嵌套。
create table student1(
id int,
name string,
scores array
);
插入数据格式
{1, 'chb', [89, 90, 100]}
create table student2(
id int,
name string,
scores map
);
插入数据格式:
{1, 'chb', }
create table student3(
id int,
scores array
);
插入数据格式:
{1, 'chb', [, }
create table student4(
id int,
info struct
);
插入数据格式:
{1, {'chb', 23, '男'}}
2.1、三种复杂类型的创建,及数据导入,查询
##结构体 struct
create table t1 (
id int,
info struct
)
row format delimited fields terminated by ','
collection items terminated by ':';
###测试数据
[hive@test ~]$ cat struct
1,dd:20
2,cc:23
3,ee:78
[hive@test ~]$
###加载数据
load data load input "/home/hive/struct" into table t1;
###struct的查询 使用字段名.元素名 即info.name
hive> select id , info.name, info.age from t1;
OK
1 dd 20
2 cc 23
3 ee 78
Time taken: 0.453 seconds, Fetched: 3 row(s)
hive>
###array
create table t2(
name string,
list array)
row format delimited fields terminated by "," -- 字段之间的分割符
collection items terminated by ":"; -- 集合元素之间的分割符
##测试数据
[hive@test ~]$ cat array
zhangsan,12:13:14
li,23:24:25
[hive@test ~]$
##加载数据
load data load input "/home/hive/array" into table t2;
###array的查询,使用字段名[元素索引] 即list[0]
hive> select name, list[0] from t2;
OK
zhangsan 12
li 23
Time taken: 0.46 seconds, Fetched: 2 row(s)
hive>
###map
create table t3(
id int,
scores map)
row format delimited fields terminated by "|" -- 字段之间的分割符
collection items terminated by "," -- 结合元素之间的分割符
map keys terminated by ":"; -- map中keyvalue的分割符
###测试数据
[hive@idc007129 ~]$ cat map
1|aa:12,bb:23,cc:55
2|aa:90,bb:89,cc:23
[hive@idc007129 ~]$
###加载数据
load data local inpath "/home/hive/map" into table t3;
###map的查询, 有些区别使用 字段名.['元素名'], 注意“'”, scores['aa']
hive> select id, scores['aa'] from t3;
OK
1 12
2 90
Time taken: 0.453 seconds, Fetched: 2 row(s)
hive> select * from t3;
OK
1 {"aa":12,"bb":23,"cc":55}
2 {"aa":90,"bb":89,"cc":23}
Time taken: 0.457 seconds, Fetched: 2 row(s)
hive>