一 基本概念
类型 | 描述 | 语法 | 举例 |
---|---|---|---|
array | 一组相同类型数据的集合 | ARRAY<data_type> | 如果数组值为[‘John’, ‘Doe’],那么第2个元素可以通过数组名[1]进行引用 |
map | 一组键-值对数据的集合,使用key可以访问值 | MAP<primitive_type, data_type> | 如果某列的数据类型是MAP,其中键->值对是’first’->’John’和’last’->’Doe’,那么可以通过字段名[‘last’]获取值’Doe’ |
struct | 一组不同数据类型的集合,可以通过”点”符号访问元素 | STRUCT<col_name : data_type [COMMENT col_comment], ...> | 如果某列的数据类型是STRUCT{first STRING, ladt STRING},那么第1个元素可以通过字段名.first来引用 |
二 示例
1 在库practice中创建表person
use practice;
drop table if exists person;
create table person(
name string,
hobby array<string> comment 'array中元素均为string类型',
score map<string,int> comment 'map中键为string类型,值为int类型',
feature struct<height:int,brand:string> comment 'struct中height类型为int,类型为string'
)
row format delimited fields terminated by ',' -- 字段之间用','分隔
collection items terminated by '_' -- 集合中的元素用'_'分隔
map keys terminated by ':' -- map中键值对之间用':'分隔
stored as textfile; -- 保存为textfile类型
2 数据
张三,唱歌_跳舞,数学:90_语文:80_英语:70,186_鸿星尔克
李四,篮球_足球_排球,数学:60_历史:50,176_李宁
王五,围棋_象棋_五子棋_军旗,语文:40,166_安踏
刘六,睡觉,政治:30_地理:20,156_特步
3 导入数据
load data local inpath '/home/zhs/Documents/data_test.txt'
into table practice.person;
4 查看数据
select * from practice.person;
5 Array的查询
select name,hobby[1] as hob from person;
-- 输出如下内容
张三 跳舞
李四 足球
王五 象棋
刘六 NULL
select array(111,222,333);
-- 输出如下内容
[111,222,333]
6 Map的查询
select name,score['语文'] from person;
-- 输出如下内容
张三 80
李四 NULL
王五 40
刘六 NULL
select str_to_map('key1:11#key2:22#key3:33',"#",":");
-- 输出如下内容
{"key1":"11","key2":"22","key3":"33"}
7 Struct的查询
select name,feature.brand from person;
-- 输出如下内容
张三 鸿星尔克
李四 李宁
王五 安踏
刘六 特步
三 扩展:一行变多行
explode()函数用于打散行(将一行的数据拆分成多行,它的参数必须为map或array)
Lateral View 用于和UDTF函数【explode,split】结合来使用
首先通过UDTF函数将数据拆分成多行,再将多行结果组合成一个支持别名的虚拟表
语法:LATERAL VIEW udtf(expression) tableAlias AS columnAlias
hive> select explode(hobby) from person;
唱歌
跳舞
篮球
足球
排球
围棋
象棋
五子棋
军旗
睡觉
hive> select explode(score) from person;
数学 90
语文 80
英语 70
数学 60
历史 50
语文 40
政治 30
地理 20
hive> select name, hobby_all
> from person
> lateral view explode(hobby) hobbyTable as hobby_all;
张三 唱歌
张三 跳舞
李四 篮球
李四 足球
李四 排球
王五 围棋
王五 象棋
王五 五子棋
王五 军旗
刘六 睡觉
hive> select name, score_1, score_2
> from person
> lateral view explode(score) scoreTable as score_1, score_2 ;
张三 数学 90
张三 语文 80
张三 英语 70
李四 数学 60
李四 历史 50
王五 语文 40
刘六 政治 30
刘六 地理 20
hive> select name, hobby_all, score_1, score_2
> from person
> lateral view explode(hobby) hobbyTable as hobby_all
> lateral view explode(score) scoreTable as score_1, score_2;
张三 唱歌 数学 90
张三 唱歌 语文 80
张三 唱歌 英语 70
张三 跳舞 数学 90
张三 跳舞 语文 80
张三 跳舞 英语 70
李四 篮球 数学 60
李四 篮球 历史 50
李四 足球 数学 60
李四 足球 历史 50
李四 排球 数学 60
李四 排球 历史 50
王五 围棋 语文 40
王五 象棋 语文 40
王五 五子棋 语文 40
王五 军旗 语文 40
刘六 睡觉 政治 30
刘六 睡觉 地理 20