集合类型主要包括:array,map,struct等,hive的特性支持集合类型,这特性是关系型数据库所不支持的,利用好集合类型可以有效提升SQL的查询速率。
集合类型之Array
collection items terminated by '-';
这就是指定集合类型的分隔符
- 先创建一张表
create table t_array(id int,name string,hobby array<string>)
row format delimited
fields terminated by ','
collection items terminated by '-';
- 准备数据文件 /opt/array.txt
1,zhangsan,唱歌-跳舞-游泳
2,lisi,打游戏-篮球
- 加载数据文件到t_array表中
hive> load data local inpath '/opt/array.txt' into table t_array;
- 查询数据
select id ,name,hobby[0],hobby[1] from t_array;
注意:array的访问元素和java中是一样的,这里通过索引来访问。
集合类型之Map
map keys terminated by ':' ;
map的分割符,就是k-v键值对之间的分割符。
- 先创建一张表
create table t_map(id int,name string,hobby map<string,string>)
row format delimited
fields terminated by ','
collection items terminated by '-'
map keys terminated by ':' ;
- 准备数据文件 map.txt
1,zhangsan,唱歌:非常喜欢-跳舞:喜欢-游泳:一般般
2,lisi,打游戏:非常喜欢-篮球:不喜欢
- 加载数据文件到t_map表中
load data local inpath '//map.txt' into table t_map;
- 查询数据
select id,name,hobby['唱歌'] from t_map;
注意:map的访问元素中的value和java中是一样的,这里通过key来访问。
集合类型之Struct
和C语言中的struct类似,都可以通过"点"符号访问元素内容.例如,如果某个列的数据类型是STRUCT{first STRING, last STRING},那么第一个元素可以通过字段.first来应用。
- 先创建一张表
create table t_struct(id int,name string,address struct<country:string,city:string>)
row format delimited
fields terminated by ','
collection items terminated by '-';
- 准备数据文件 struct.txt
1,zhangsan,china-beijing
2,lisi,USA-newyork
- 加载数据文件到t_struct表中
load data local inpath '//struct.txt' into table t_struct;
- 查询数据
select id,name,address.country,address.city from t_struct;
select id,name,address.country,address.city from t_struct;