本文为转载,原文链接:

https://blog.csdn.net/lixiaoksi/article/details/106919895

https://blog.csdn.net/elizabethxxy/article/details/108912884

本文总结hive中清空外部表的三种方式

hive版本:2.1.1

环境准备

新建一张外部表:

create external  table test_external (name String,age int,sex String) stored as orc;

插入数据:

insert into table test_external values("johnson",18,"男");

查看数据:

如果此时使用truncate 命令的话,会抛出错误信息 FAILED: SemanticException [Error 10146]: Cannot truncate non-managed table test_external.

那如果在实际场景中,需要去清空外部表,我们该怎么办呢?

方式一:将外部表文件所在目录指定成一个空的目录

alter table test_external set location 'hdfs://bd227:8020/opt/hive/warehouse/test_external_like';

注:此方式并没有清空外部表之前所指定路径下的文件。

方式二:使用命令 set TBLPROPERTIES('EXTERNAL'='false')  将外部表变为内部表后,执行truncate命令,然后再更改为外部表

1:alter table test_external  set TBLPROPERTIES('EXTERNAL'='false');

此时查看建表语句,external关键字已不存在,说明已变成了受hive meta store 管理的内部表

2:truncate table test_external;

执行truncate 命令,将表清空,查看hdfs上对应表的路径下,文件也一并被清空

3:alter table test_external  set TBLPROPERTIES('EXTERNAL'='true');

将表属性更改为外部表 set TBLPROPERTIES('EXTERNAL'='true') 

方式三:使用 insert overwrite 语句代替实现 truncate 功能

1:新建一张临时表 test_external_temp; 该表结构与外部表的表结构一样。

 create temporary table  test_external_temp (name String,age int,sex String) stored as orc;

注意:该临时表只对当前会话有效。倘若你创建了临时表,重新打开一个hive cli,此时你找不到这张表

2:执行 insert overwrite table test_external select * from test_external_temp; 使用overwrite 关键字执行了清空表操作

 

补充:根据官网描述 

Starting Hive 4.0.0 ( HIVE-19981 - Managed tables converted to external tables by the HiveStrictManagedMigration utility should be set to delete data when the table is dropped RESOLVED  ) setting table property external.table.purge=true, will also delete the data.   

Hive 4.0.0开始,亦可使用 external.table.purge=true 也可清空表数据。

Logo

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

更多推荐