基本数据类型
集合数据类型
集合实操示例
假设某表有如下一行,我们用 JSON 格式来表示其数据结构。在 Hive 下访问的格
式为
{
"name": "songsong",
"friends": ["bingbing" , "lili"] , //列表 Array,
"children": { //键值 Map,
"xiao song": 18 ,
"xiaoxiao song": 19
}
"address": { //结构 Struct,
"street": "hui long guan",
"city": "beijing"
}
}
- 基于上述数据结构,我们在 Hive 里创建对应的表,并导入数据。创建本地测试文件 test.txt
songsong,bingbing_lili,xiao song:18_xiaoxiao song:19,hui long guan_beijing
yangyang,caicai_susu,xiao yang:18_xiaoxiao yang:19,chao yang_beijing
- Hive 上创建测试表 test1
create table test1(
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’:行分隔符
- 导入文本数据到测试表
load data local inpath '/opt/module/hive/datas/test1.txt' into table test1;
- 访问三种集合列里的数据,以下分别是 ARRAY,MAP,STRUCT 的访问方式
select friends[1],children['xiao song'],address.city from
test1
where name="ongsong";
类型转化
Hive 的原子数据类型是可以进行隐式转换的,类似于 Java 的类型转换。
例如某表达式使用 INT 类型,TINYINT 会自动转换为 INT 类型。
但是 Hive 不会进行反向转化,例如,某表
达式使用 TINYINT 类型,INT 不会自动转换为 TINYINT 类型,它会返回错误,除非使用 CAST操作。
规则
- 任何整数类型都可以隐式地转换为一个范围更广的类型,如 TINYINT 可以转换成INT,INT 可以转换成 BIGINT。
- 所有整数类型、FLOAT和STRING 类型都可以隐式地转换成DOUBLE。
- TINYINT、SMALLINT、INT 都可以转换为 FLOAT。
- BOOLEAN 类型不可以转换为任何其它的类型。
CAST 进行数据类型转换
例如
CAST(‘1’ AS INT)将把字符串’1’ 转换成整数 1;
如果强制类型转换失败,如执行
CAST(‘X’ AS INT),表达式返回空值 NULL。