map 结构
1. 语法:map(k1,v1,k2,v2,…)
操作类型:map ,map类型的数据可以通过'列名['key']的方式访问
案例:
select deductions['Federal Taxes'],deductions['State Taxes'],
deductions['Insurance']
from employees
limit 1;
(1)如果没有查到结果可以使用if判断:
select if(deductions['Federal Taxes'] is null, 0, deductions['Federal Taxes'])
from employees
limit 1;
(2)我们也可以用UDTF把结果变成多行,比如:
select explode(deductions) from employees;
(3)有时候我们需要把name也查询出来:
错误写法:
select name, explode(deductions) from employees;
注意,Explode单独使用只能单个字段,如果要和别的字段一起使用必须使用lateral view explode
正确写法:
select name,dekey,devalue
from employees
LATERAL VIEW explode(deductions) dedView as dekey,devalue;
2. 查询方法
原表数据如下:
(1)map_values(map):取map字段全部value
%jdbc(hive)
select cookie,map_values(mid)
from temp.map_20181101
(2)使用下标访问map
%jdbc(hive)
select cookie,mid['2024']
from temp.map_20181101
(3)size()查看map长度即有多少键值对
%jdbc(hive)
select cookie,size(mid)
from temp.map_20181101
(4)Lateral View语法将值展开为一个新的虚拟表
%jdbc(hive)
SELECT cookie,fixeddim_key,fixeddim_value
FROM temp.map_20181101
LATERAL VIEW explode(mid) myTable1 AS fixeddim_key,fixeddim_value
3. 创建含map数据类型的表和数据插入形式
(1) 建表:
hive> CREATE TABLE t3 (foo STRING, bar MAP<STRING,INT>)
> ROW FORMAT DELIMITED
> FIELDS TERMINATED BY '/t'
> COLLECTION ITEMS TERMINATED BY ','(必须使用)
> MAP KEYS TERMINATED BY ':'
> STORED AS TEXTFILE;