探究Hive中的数据类型

2023-10-16 大数据Hive

hive作为一个类似数据库的框架,也有自己的数据类型,便于存储、统计、分析。 Hive中主要包含两大数据类型:

  • 基本数据类型:常用的有INT,STRING,BOOLEAN,DOUBLE等,如下列表格
  • 复合数据类型:常用的有ARRAY,MAP,STRUCT等
类型 描述 示例
TINYINT(tinyint) 一个字节(8位)有符号整数, -128~127 1
SMALLINT(smallint) 2字节(16位)有符号整数,-32768~32767 1
INT(int) 4字节(32位)有符号整数 1
BIGINT(bigint) 8字节(64位)有符号整数 1
FLOAT(float) 4字节(32位)单精度浮点数 1.0
DOUBLE(double) 8字节(64位)双精度浮点数 1.0
DECIMAL(decimal) 任意精度的带符号小数 1.0
BOOLEAN(boolean) true/false true/false
STRING(string) 字符串,变长 ‘a’,‘b’,‘1’
VARCHAR(varchar) 变长字符串 ‘a’
CHAR(char) 固定长度字符串 ‘a’
BINANY(binany) 字节数组 无法表示
TIMESTAMP(timestamp) 时间戳,纳秒精度 122327493795
DATE(date) 日期 ‘2016-03-29’

# 复合数据类型——Array

建表语句如下,使用时把注释删除

create table stu (
   id int,
   name string,
   favors array<string>
) row format delimited
fields terminated by '\t'  -- 列分隔符
collection items terminated by ','
lines terminated by '\n'; -- 行分隔符,这要放在最后一行

源数据是这样的,我们使用命令load data local inpath '/data/soft/hivedata/stu.data' into table stu;插入

1	zhangsan	sing,swing,java
2	wuqi	music,vue
3	yufei	uniapp,react,spring

查询时还有特殊的语法:

select id,name,favors[0] from stu; -- 可以只查询一列,如果该列没有数据显示NULL
select id,name,favors[0] from stu; -- 查询完整数据,使用select * 也可以

# 复合数据类型——Map

create table stu2 (
    id int,
    name string,
    scores map<string,int>
) row format delimited
fields terminated by '\t'
collection items terminated by ',' -- map数据直接的划分
map keys terminated by ':' -- key/value之间的划分符号
lines terminated by '\n';


源数据是这样的,我们使用命令load data local inpath '/data/soft/hivedata/stu2.data' into table stu2;插入

1	zhangsan	chinese:80,math:90,english:100
2	wuqi	chinese:50,math:90,english:26

查询案例:

select id,name,scores from stu2;
select id,name,scores['math'] from stu2;
select id,name,scores['math'],scores['english'] from stu2;

# 复合数据类型——Struct

有点像java中的对象,比如地址信息,每个实习生都有地址信息,一个是户籍地所在的城市,一个是公司所在的城市,SQL建表如下:

create table stu3(
    id int,
    name string,
    address struct<home_addr:string,office_addr:string>
) row format delimited
fields terminated by '\t'
collection items terminated by ','
lines terminated by '\n';

源数据是这样的,我们使用命令load data local inpath '/data/soft/hivedata/stu3.data' into table stu3;插入

1	zhangsan	bj,sh
2	wuqi	gz,sz

查询案例:

select id,name,address.home_addr from stu3;
select id,name,address.home_addr,address.office_addr from stu3;
上次更新: 4 个月前