hive中清空外部表的三种方式

本文总结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,"男");

查看数据:

img

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

img

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

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

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

img

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

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

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

img

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

2:truncate table test_external;

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

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

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

img

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

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

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

img

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

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

原文地址:https://www.cnblogs.com/deepJL/p/14970645.html