您的位置:首页 > 运维架构

HiveQL:视图

2017-02-15 15:04 423 查看
视图可以允许保存一个查询并想对待表一样对这个查询进行操作。

使用视图来降低查询复杂度

比如以下这个例子:

hive> from(
select * from people join cart
on (cart.people_id=people_id) where firstname='join'
) a select a.lastname where a.id=3;


可以使用视图来变成下面这两条HiveQL:

hive> create view shorter_join as
select * from people join cart
on (cart.people_id=people.id) where firstname='join';

hive> select lastname from shorter_join where id=3;


使用视图来限制基于条件过滤的数据

通过创建视图来限制数据访问可以用来保护信息不被随意查询:

比如我们有一张用户信息表,里面含有password之类的不想被别人查询到的信息,那就可以创建view来保护应用:

hive> create table userinfo(
firstname string,lastname string,ssn string,password string);

hive> create view safer_user_info as
select firstname,lastname from userinfo;


动态分区中的视图和map类型

Hive可将一行文本作为一个map而非一组固定的列,加上视图功能,就允许用户可以基于同一个物理表构建多个逻辑表。比如我们有如下的数据,其中^A作为集合内元素间的分隔符(这里就是指map的多个键值对之间的分隔符),然后使用^B作为map中的键和值之间的分隔符:

time^B2325543653513^Atype^Brequest^Astate^Bny^Acity^Bwhitepains^Apart^Bmuffler


下面我们来创建表:

create external table dynamictable(cols map) hljs vbnet">row format delimited
fiflds terminated by '\004'
collection items terminated by '\001'
map keys terminated by '\002'
stored as textfile;


现在我们可以创建这样一个视图,其仅取type值等于request的city、state和part3个字段:

hive> create view order(state,city,part) as
select cols["state"],cols["city"],cols["part"]
from dynamictable
where clos["type"]="request";


我们再创建第二个视图,返回time和part2个字段作为列,限制条件死type值为response:

hive> create view shipments(time,part) as
select cols["time"],cols["part"]
from dynamictable
where cols["type"]="response";


其他

创建视图时也是可以使用一些子句的:

hive> create view if not exists shipments(time,part)
comment 'Time and parts for shipments.'
tblproperties ('creator'='me')
as select ...;


删除视图:

hive> drop view id exists shipments;


create table…like…结构同样适用于复制视图,只需在like表达式里面写视图名就可以了:

hive> create table shipments2
like shipments;


附我在开源中国的原文:

https://my.oschina.net/lonelycode/blog/837398
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Hive Hadoop HiveQL