Hive内部表:默认创建的表就是内部表。Hive完全管理表(元数据和数据)的生命周期,类似于RDBMS的表。当删除表时,它会删除源数据以及表的元数据。

Hive外部表:外部表的数据不是Hive拥有或者管理的,只管理元数据的生命周期。要创建一个外部表,需要使用external关键字。删除外部表时只会删除元数据,而不会删除实际数据(源数据)。在hive外部依然可以访问实际数据(HDFS)

下面我们将用一个关于NBA球员分析的数据进行区别内部表和外部表。

创建内部表t1

-- 创建有一个内部表t1
drop table if exists t1;
create table t1(
                      name string comment '名字',
                      pos string comment '位置',
                      height double comment '身高',
                      weight int comment '体重',
                      age int comment '年龄',
                      nba_age int comment '球龄',
                      nums int comment '出场次数',
                      avgtime double comment '平均时间',
                      attack double comment '进攻能力',
                      defend int comment '防守能力',
                      allstar string comment '是否进入全明星',
                      income bigint comment '薪资'
) comment "NBA球员分析"
row format delimited
fields terminated by ',';

-- 查看表结构
desc formatted t1;

这里有个table type标明MANAGED_TABLE说明这个表是受监管的。也就是内部表。

创建外部表t2

-- 创建外部表t2
drop table if exists t2;
create external table t2(
                      name string comment '名字',
                      pos string comment '位置',
                      height double comment '身高',
                      weight int comment '体重',
                      age int comment '年龄',
                      nba_age int comment '球龄',
                      nums int comment '出场次数',
                      avgtime double comment '平均时间',
                      attack double comment '进攻能力',
                      defend int comment '防守能力',
                      allstar string comment '是否进入全明星',
                      income bigint comment '薪资'
) comment "NBA球员分析"
row format delimited
fields terminated by ',';

-- 查看表结构
desc formatted t2;

将数据导入到两个表之间然后删除

-- 数据载入t1,t2
load data inpath '/NBA.txt' into table t1;
load data inpath '/NBA.txt' into table t2;
select * from t1;
select * from t2;

查看HDFS端口9870:删除前

 删除后

 HDFS上只有t2的源数据还在,但是它的元数据已经没有了。这里显示表找不到。

而t1在HDFS源数据直接被删除以及元数据也被删除。因为它是内部表。

所以我们在选择建表时,当需要通过Hive完全管理控制表的整个生命周期时,请使用内部表。

当文件已经存在或位于远程位置时,请使用外部表,因为即使删除表,文件也会被保留。

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐