Hive:数据类型及其基础使用
1. Array
1.在建含有数组的表时,数组字段的类型为array<string>
2.需要指定数组中的元素分隔符,下面使用 "," 来分隔
collection items terminated by ','
3.通过xxx[index] 选取某个数组中的元素,其中xxx为数组字段名,index为下标。
– 举例:
1)数据:
重庆市 渝中区, 江北区, 南岸区, 沙坪坝区, 九龙坡区, 渝北区, 大渡口区, 巴南区, 北碚区
山西省 太原市, 大同市, 忻州市, 运城市, 晋中市
2) 使用
create table if not exists t_arr(
province string,
city array< string>
)
row format delimited
fields terminated by '\t'
collection items terminated by ',' ;
load data local inpath '/root/arr.txt' into table t_arr;
hive ( hive) > select province, city[ 1 ] from t_arr;
OK
重庆市 江北区
山西省 大同市
2. Map
1.在建含有map类型的表时,map字段的类型为map<type1,type2>,type1是key的类型,type2是value的类型
2.需要指定map中的每一个<key,value>的分隔符和key,value之间的分隔符,下面使用 "," 来分隔每一个<key,value>;使用":"来分隔key和value之间的分隔符。
collection items terminated by ',' map元素之间
map keys terminated by ':' key和value之间
3.通过xxx[key] 选取某个数组中的元素,其中xxx为map字段名,返回key对应的value。
–举例
1) 数据
小米 手机:3999 , 电视:2999 , 手环:199 , 热水器:169
华为 手机:4999 , 笔记本电脑:7999 , 手环:239
2)使用
create table if not exists t_map(
name string,
comm map< string, int >
)
row format delimited
fields terminated by '\t'
collection items terminated by ','
map keys terminated by ':' ;
load data local inpath '/root/map.txt' into table t_map;
hive ( hive) > select name, comm[ '手环' ] from t_map;
OK
小米 199
华为 239
3. Struct
1.在建含有结构体的表时,指定结构体的类型为struct<describe1:type1,describe2:type2,describe3:type3>
describe为每个结构层名,type为类型
2.结构体的数据和数据的数组十分类似,结构体更像是一个对象
3.结构体中的元素分隔符,设置的时候和数组一样,下面使用 "," 来分隔
collection items terminated by ','
3.取结构体的属性值,字段名.属性名
–举例
1)数据
林志玲 台湾省, 台北市, 台中街道
杨幂 上海市, 浦东区, xxx街道
2)使用
create table if not exists t_str(
name string,
item_id struct< province:string, city:string, street:string>
)
row format delimited
fields terminated by '\t'
collection items terminated by ',' ;
load data local inpath '/root/str.txt' into table t_str;
hive ( hive) > select name, item_id. city from t_str;
OK
林志玲 台北市
杨幂 浦东区
4.explode:行转列
–explode: 数组或映射作为参数
1) 基础用法
select explode( city) from t_arr;
渝中区
江北区
南岸区
沙坪坝区
九龙坡区
渝北区
大渡口区
巴南区
北碚区
太原市
大同市
忻州市
运城市
晋中市
select explode( comm) from t_map;
手机 3999
电视 2999
手环 199
热水器 169
手机 4999
笔记本电脑 7999
手环 239
2) 误区
这个explode将一行数据转换成多行不能与该表中的其他字段连用。
hive> select province,explode(city) from t_arr;
FAILED: SemanticException [Error 10081]: UDTF's are not supported outside the SELECT clause, nor nested in expressions
–Lateral View
1) 使用
LATERAL VIEW udtf( expression) tableAlias AS columnAlias ( ',' columnAlias) *
fromClause: FROM baseTable ( lateralView) *
select province, ccity
from t_arr lateral view explode( city) scity as ccity;
重庆市 渝中区
重庆市 江北区
重庆市 南岸区
重庆市 沙坪坝区
重庆市 九龙坡区
重庆市 渝北区
重庆市 大渡口区
重庆市 巴南区
重庆市 北碚区
山西省 太原市
山西省 大同市
山西省 忻州市
山西省 运城市
山西省 晋中市
select name, co, count
from t_map lateral view explode( comm) c as co , count;
小米 手机 3999
小米 电视 2999
小米 手环 199
小米 热水器 169
华为 手机 4999
华为 笔记本电脑 7999
华为 手环 239