hql 中数组的使用

本文介绍HQL如何操作数组和Map数据类型。包括创建数据库、数据准备及表数据查看。重点讲解了如何使用`split`、`explode`函数对数组进行拆分,以及`inline`函数处理Map类型数据,输出为两列。
摘要由CSDN通过智能技术生成
hql 中数组的使用
explode 函数
posexplode 函数

创建数据库 array_map 并使用

create databases array_map;
use array_map;

-- 设置本地模式
set hive.exec.mode.local.auto=true;

数据准备

vim /opt/module/datas/over/student.txt

zs	语文:86,数学:87.5,英语:90
ls	语文:76,数学:93,英语:88
ww	语文:88,数学:90,英语:95

创建两张表 student_array student_map 并导入数据

create table student_array(
name string,
course_score array<string>) 
row format delimited fields terminated by '\t' 
collection items terminated by ',';

load data local inpath '/opt/module/datas/over/student.txt' into table student_array;

create table student_map(
name string,
course_score map<string ,float>)
row format delimited fields terminated by '\t'
collection items terminated by ','
map keys terminated by ':';

load data local inpath '/opt/module/datas/over/student.txt' into table student_map;

查看表数据

student_array

select * from student_array;
------------------------------------
student_array.name	student_array.course_score
zs	["语文:86","数学:87.5","英语:90"]
ls	["语文:76","数学:93","英语:88"]
ww	["语文:88","数学:90","英语:95"]

student_map

select * from student_map;
------------------------------------
student_map.name	student_map.course_score
zs	{"语文":86.0,"数学":87.5,"英语":90.0}
ls	{"语文":76.0,"数学":93.0,"英语":88.0}
ww	{"语文":88.0,"数学":90.0,"英语":95.0}

对于array 类型的数据, explode 函数将数组中的元素拆分,按行输出每个元素

select explode(course_score) from student_array;
------------------------------------
col
语文:86
数学:87.5
英语:90
语文:76
数学:93
英语:88
语文:88
数学:90
英语:95

posexplode 函数类似于 explode函数,只是在返回数组中的元素同时也返回元素在数组中的索引位置

select posexplode(course_score) from student_array;
------------------------------------
pos	val
0	语文:86
1	数学:87.5
2	英语:90
0	语文:76
1	数学:93
2	英语:88
0	语文:88
1	数学:90
2	英语:95

对于map数据类型,explode 函数会将一个map数据类型拆分成两列输出,键一列,值一列。

select explode(course_score) from student_map;
------------------------------------
key	value
语文	86.0
数学	87.5
英语	90.0
语文	76.0
数学	93.0
英语	88.0
语文	88.0
数学	90.0
英语	95.0

posexplode 函数的参数只能是数组,不能是map数据类型

hive (overstudy)> select posexplode(course_score) from student_map;
FAILED: UDFArgumentException posexplode() takes an array as a parameter
hive (overstudy)> select posexplode(course_score) from student_array;
OK
pos	val
0	语文:86
1	数学:87.5
2	英语:90
0	语文:76
1	数学:93
2	英语:88
0	语文:88
1	数学:90
2	英语:95
0	语文:86
1	数学:87.5
2	英语:90
0	语文:76
1	数学:93
2	英语:88
0	语文:88
1	数学:90
2	英语:95
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值