本文参考
hive 内部表和外部表的区别和理解 ,加入实例。
创建表
语法:
CREATE [EXTERNAL] TABLE [IF NOT EXISTS] [db_name.]table_name
(col_name data_type [COMMENT col_comment], ...)
[PARTITIONED BY (col_name data_type, ...)]
[CLUSTERED BY (col_name, col_name, ...) [SORTED BY (col_name [ASC|DESC], ...)] INTO num_buckets BUCKETS]
[ROW FORMAT row_format]
[STORED AS file_format]
[LOCATION hdfs_path]
其中,[]里面的都是可选项。
内部表
hive创建的默认是内部表。若创建时不指定location,就会在/user/hive/warehouse/下新建一个表目录。 例如,在test数据库下创建表tt:
create table tt(
id int,
str string)
row format delimited fields terminated by ',';
 若指定location,比如说是/user/root/in:
create table tt(
id int,
str string)
row format delimited fields terminated by ','
location '/user/root/in';
 用hive命令导入本地数据:
load data local inpath '/home/hadoop/tt.txt' into table tt;
 
删除tt表后,会将表内的数据和元数据信息全部删除,即/user/root/in下无数据。 删除tt表:
drop table tt;
 可见,tt已被删除。
外部表
创建外部表external_tt:
create external table external_tt(
id int,
str string)
row format delimited fields terminated by ','
location '/user/root/out';
 导入数据
load data local inpath '/home/hadoop/tt.txt' into table external_tt;

删除tt表:
drop table external_tt;
 tt.txt仍在。
内部表与外部表的区别
- 在导入数据到外部表,数据并没有移动到自己的数据仓库目录下(如果指定了location的话),也就是说外部表中的数据并不是由它自己来管理的;
- 在删除内部表的时候,hive将会把属于表的元数据和数据全部删掉;而删除外部表的时候,hive仅仅删除外部表的元数据,数据是不会删除的;
- 在创建内部表或外部表时加上location 的效果是一样的,只不过表目录的位置不同。加上partition用法也一样,只不过表目录下会有分区目录而已,“load data”和“local inpath”能直接把本地文件系统的数据上传到hdfs上,有location上传到location指定的位置上,没有的话上传到hive默认配置的数据仓库中。
|