map 結構 1. 語法:map(k1,v1,k2,v2,…) 1. 語法:map(k1,v1,k2,v2,…) 操作類型:map ,map類型的數據可以通過'列名['key']的方式訪問 案例: select deductions['Federal Taxes'],deductions['Stat ...
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;