先建立一个内部表:
建表语句-进入hive命令行输入:
create table t1(
id int
,name string
,hobby array<string>
,add map<String,string>
)
row format delimited
fields terminated by ','
collection items terminated by '-'
map keys terminated by ':'
;
查看表结构:
desc t1;
可以使用hiveserver2进行格式化的查询:
往表中插入数据。
我们先看一下hdfs文件系统,里面在 /user/hive/warehouse/test01.db/t1
这个目录里面什么都没有。
我们使用hadoop上传一个符合格式的文件到这个目录。
插入t1表中的数据:
1,xiaoming,book-TV-code,beijing:chaoyang-shagnhai:pudong
2,lilei,book-code,nanjing:jiangning-taiwan:taibei
3,lihua,music-book,heilongjiang:haerbin
hadoop fs -put t1.txt /user/hive/warehouse/test01.db/t1
这个t1.txtx文件上传成功。
只要上传了,这些数据就会插入到t1表中。
创建一个外部表:
create external table t2(
id int
,name string
,hobby array<string>
,add map<string,string>
)
row format delimited
fields terminated by ','
collection items terminated by '-'
map keys terminated by ':'
location '/user/hive/warehouse/'
;
看我写的这个路径 loaction ‘/user/hive/warehouse/’
在这个路径下面本来是有test01.db这个文件夹的,在test01.db里面有我之前上上传的t1.txt。
然后上传数据:
load data local inpath '/home/hadoop/apps/hiveData' overwrite into table t2;
然后查询t2表就会发现会有数据:
但是奇怪的是:
/user/hive/warehouse 目录下面只有t1.txt,其他的什么都没了,之前的test01.db文件也没了。
再次查询t1表,发现里面真的没数据了,但是表还在。太奇怪了。
【个人对上面出现的问题的理解:】
首先我发现了这么一个现象:
我如果创建了一个数据库,假设我创建了test03这个数据库:
那么在hdfs文件系统里的 /user/hive/warehouse
这个目录下面会出现这个文件:
test03.db
如果我现在创建一个外部表t2:
create external table t2(
id int
,name string
,hobby array<string>
,add map<string,string>
)
row format delimited
fields terminated by ','
collection items terminated by '-'
map keys terminated by ':'
location '/user/d3t2'
/user/d3t2 这个目录一开始是没有的,一旦我将t2这个外部表创建成功,那么这个 /user/d3t2 目录也会被创建。
这个是hive自动调用hadoop程序创建的,一开始里面什么都没有。
然后我们往这个 /user/d3t2里面加载数据。
load data local inpath '/home/hadoop/apps/hiveData/t2.txt' overwrite into table t2;
表里面的数据就生成了。
t2.txt 文件也会加载建表时设置的
如果此时我建一个内部表,
create table t1(
id int
,name string
,hobby array<string>
,add map<string,string>
)
row format delimited
fields terminated by ','
collection items terminated by '-'
map keys terminated by ':'
;
此时在hdfs文件系统中的目录下面 /user/hive/warehouse/test03.db
会有一个t1文件夹。
刚开始这个t1文件夹里面,当我们使用hadoop fs -put 将符合t1表格式的文件上传到这个文件夹里面,那么这个文件里面的数据都插入到t1表中。
hadoop fs -put t1.txt /user/hive/warehouse/test03.db/t1
t1表的数据已经被插入:
一旦我把这个表drop掉,hdfs文件系统里面的t1.txt也会消失。
hadoop fs -rm -r /user/hive/warehouse/test03.db/t1/t1.txt
表里面的数据就被删除了:
当把外部表的外部数据文件也删除,那么外部表里面的数据也会清空。
一旦使用 drop table t1
把内部表删除了,那么这张表会被删除,对应的表插入的数据文件也会被删除。数据是没法被恢复的。
但是对于外部表而言,即使是使用 drop table t2 将外部表删除,但是只要表里面的数据文件 t1.txt文件没删除的话,重新使t2的建表语句,执行一下,这张表里面的数据就会被恢复。
有关内部表与外部表的区别可以参考下面这篇博客: