1. 程式人生 > >Hive 內表與外表的區別

Hive 內表與外表的區別

一、區別

1、建立表結構

①在Hive裡面建立一個表:

hive> create table wyp(id int,
    > name string,
    > age int,
    > tele string)
    > ROW FORMAT DELIMITED
    > FIELDS TERMINATED BY '\t'
    > STORED AS TEXTFILE;
OK
Time taken: 0.759 seconds

②建立外部表多了external關鍵字說明以及location ‘/home/wyp/external’

hive> create external table exter_table(
    > id int,
    > name string,
    > age int,
    > tel string)
    > location '/home/wyp/external';
OK
Time taken: 0.098 seconds

建立外部表,需要在建立表的時候加上external關鍵字,同時指定外部表存放資料的路徑(當然,你也可以不指定外部表的存放路徑,這樣Hive將 在HDFS上的/user/hive/warehouse/資料夾下以外部表的表名建立一個資料夾,並將屬於這個表的資料存放在這裡)

2. 資料匯入和匯出

①資料匯入

內部表匯入資料,資料移動到自己的資料倉庫目錄下,由hive自己來管理

load data local inpath '/home/wyp/data/wyp.txt' into table wyp;

外部表匯入資料:load data local inpath '/home/wyp/data/wyp.txt' into table exter_table;

在匯入資料到外部表,資料並沒有移動到自己的資料倉庫目錄下,也就是說外表中的資料並不是由它自己來管理的;

②資料匯出

內部表匯出:

資料是從本地檔案系統複製到HDFS中/home/hdfs/wyp.txt檔案中

外部表匯出:

       資料是從本地檔案系統複製到HDFS中/home/hdfs/wyp.txt檔案中,但是,最後 資料不是移動到外部表的/user/hive/warehouse/exter_table資料夾中(除非你建立表的時候沒有指定資料的存放路徑)。大家 可以去HDFS上看看,對於外部表,資料是被移動到建立表時指定的目錄(本例是存放在/home/wyp/external資料夾中)!

3.刪除表

刪除內部表

hive> drop table wyp;
Moved: 'hdfs://mycluster/user/hive/warehouse/wyp' to 
        trash at: hdfs://mycluster/user/hdfs/.Trash/Current
OK
Time taken: 2.503 seconds

②刪除外部表
hive> drop table exter_table;
OK
Time taken: 0.093 seconds

在刪除表的時候,Hive將會把屬於表的元資料和資料全部刪掉;而刪除外部表的時候,Hive僅僅刪除外部表的元資料,資料是不會刪除的!

總結:

1、在匯入資料到外部表,資料並沒有移動到自己的資料倉庫目錄下,也就是說外部表中的資料並不是由它自己來管理的,而表則不一樣;
2、在刪除表的時候,Hive將會把屬於表的元資料和資料全部刪掉;而刪除外部表的時候,Hive僅僅刪除外部表的元資料,資料是不會刪除的!
那麼,應該如何選擇使用哪種表呢?在大多數情況沒有太多的區別,因此選擇只是個人喜好的問題。但是作為一個經驗,如果所有處理都需要由Hive完成,那麼你應該建立表,否則使用外部表!