hive内部表、外部表、分区

hive内部表、外部表、分区

内部表(managed table)
  • 默认创建的是内部表(managed table),存储位置在hive.metastore.warehouse.dir设置,默认位置是/user/hive/warehouse
  • 导入数据的时候是将文件剪切(移动)到指定位置,即原有路径下文件不再存在
  • 删除表的时候,数据和元数据都将被删除
  • 默认创建的就是内部表create table xxx (xx xxx)
外部表(external table)
  • 外部表文件可以在外部系统上,只要有访问权限就可以
  • 外部表导入文件时不移动文件,仅仅是添加一个metadata
  • 删除外部表时原数据不会被删除
  • 分辨外部表内部表可以使用DESCRIBE FORMATTED table_name 命令查看
  • 创建外部表命令添加一个external即可,即create external table xxx (xxx)
  • 外部表指向的数据发生变化的时候会自动更新,不用特殊处理
表分区(Partitioned table)
  • 有些时候数据是有组织的,比方按日期/类型等分类,而查询数据的时候也经常只关心部分数据,比方说我只想查2017年8月8号,此时可以创建分区
  • 使用partioned by (xxx)来创建表的分区,比方说
create table table_name (
  id                int,
  dtDontQuery       string,
  name              string
)
partitioned by (date string)
  • 注意,假如table里有date字段,那么分区的时候不要用date了,不然当查询的时候写where data=xxx时会出错,即下面这种情况:
create table table_name (
  id                int,
  date       string,
  name              string
)
partitioned by (date string)
  • 尽量不用date这个字,根据系统设置不同,可能会触发不同的错误,如FAILED: ParseException line 3:16 Failed to recognize predicate 'date'. Failed rule: 'identifier' in column specification,有的时候又遇不到,换一个词就好了
  • 外部表创建时也可以直接指定路径,但是此时就只能加载一个数据源了,不推荐使用
例子
  • 创建内部表以及分区
create table test(name string);
LOAD DATA INPATH '/hdfs_home/20170808' INTO TABLE test partition(date='20170808');

或

create table test_3 (name string, age int) partitioned by (date string) row format delimited fields terminated by ',' lines terminated by '\n';
LOAD DATA INPATH '/hdfs_home/20170808' INTO TABLE test partition(date='20170808');  # 指向文件夹即可

# 执行后原hdfs路径下20170808文件夹已经不存在(被移动走了)
  • 外部表及分区创建
hive> create external table test_4 (name string, age int) partitioned by (date string) row format delimited fields terminated by ',' lines terminated by '\n';
OK
Time taken: 0.121 seconds

hive> alter table test_4 add partition (date='20170809') location '/hdfs_home/20170809/';
OK

hive> select * from test_4 where date = '20170809';
OK
zhao	14	20170809

# 此时/hdfs_home/20170809还在原路径下

# 若使用以下命令进行操作,则相当于内部表的操作了,即原路径文件消失
alter table test_4 add partition (date='20170809');
load data inpath ('/hdfs_home/20170809/') into table test_4 partition (date='20170809')
  • 查看表的分区
show partitions table_name;
  • 查看是内部表还是外部表
describe extended tablename;

or

desc formatted tablename;
  • 删除分区
ALTER TABLE  table_name DROP PARTITION (day='20140722');
参考
posted @ 2017-10-23 17:51  wswang  阅读(5433)  评论(0编辑  收藏  举报