hive的集合类型Array、Map和Struct及相应的创建、插入、查询操作

hive的集合数据类型包括三种,分别是

Array、Map和Struct

下面分别介绍一下关于集合类型的创建表、插入数据以及查询的方法

1、创建包含有集合数据类型的hive表

create table test_set(
id INT,
name STRING,
hobby ARRAY<STRING>,    //array中元素为String类型
friend MAP<STRING,STRING>,    //map中键和值均为String类型
mark struct<math:int,english:int>   //Struct中元素为Int类型
)
row format delimited fields terminated by ','   //字段之间用','分隔
collection items terminated by '_'     //集合中的元素用'_'分隔
map keys terminated by ':'      //map中键值对之间用':'分隔
lines terminated by '\n       //行之间用'\n'分隔
 

2、向表test_set中插入数据

1)对于数据量较大,常用的一种方法是通过文件批量导入的方法,比如我现在要将如下的文本中的数据插入到表中

1,xiaoming,basketball_game,xiaohong:yes_xiaohua:no,99_75

1,xiaohong,watch_study,xiaoming:no_xiaohua:not,95_95

可以采用如下语句来实现

load data inpath '/uesr/xiaoming/11.txt' overwrite into table test_set

2)对于想插入几条数据时,可以采取insert语句来插入数据,比如我们想插入数据

2,xiaohua,basketball_read,xiaoming:no_xiaohong:no,90_90

可以采用如下语句来实现,分别通过array,str_to_map,named_struct来包装插入的三种集合数据

INSERT INTO test_set SELECT 2,'xiaohua',array('basketball','read'),str_to_map('xiaoming:no,xiaohong:no'),named_struct('math',90,'english',90)

3、查询表中的数据,如果要查询表中的所有数据,直接通过查询

select * from test_set

查询结果如下:

另外,对于集合类型的查询,我们还有一种经常使用的方法,查询语句如下

select id,name,hobby[0],      //查询第一个hobby
friend['xiaohong'],       //查询map键为xiaohong的value
mark.math       //查询struct中math的值
from test_set where name = 'xiaoming'
查询结果如下:

发布了355 篇原创文章 · 获赞 84 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qq_43193797/article/details/102896762