1. 程式人生 > 其它 >Hive 中內部表與外部表的區別與建立方法

Hive 中內部表與外部表的區別與建立方法

先來說下Hive中內部表與外部表的區別: Hive 建立內部表時,會將資料移動到資料倉庫指向的路徑;若建立外部表,僅記錄資料所在的路徑, 不對資料的位置做任何改變。在刪除表的時候,內部表的元資料和資料會被一起刪除, 而外部表只刪除元資料,不刪除資料。這樣外部表相對來說更加安全些,資料組織也更加靈活,方便共享源資料。 需要注意的是傳統資料庫對錶資料驗證是 schema on write(寫時模式),而 Hive 在load時是不檢查資料是否 符合schema的,hive 遵循的是 schema on read(讀時模式),只有在讀的時候hive才檢查、解析具體的 資料欄位、schema。 讀時模式的優勢是load data 非常迅速,因為它不需要讀取資料進行解析,僅僅進行檔案的複製或者移動。 寫時模式的優勢是提升了查詢效能,因為預先解析之後可以對列建立索引,並壓縮,但這樣也會花費要多的載入時間。 下面來看下 Hive 如何建立內部表:

create table test(userid string);
LOAD DATA INPATH '/tmp/result/20121213' INTO TABLE test partition(ptDate='20121213');

這個很簡單,不多說了,下面看下外部表:

hadoop fs -ls /tmp/result/20121214
Found 2 items
-rw-r--r--   3 june supergroup       1240 2012-12-26 17:15 /tmp/result/20121214/part-00000
-rw-r--r--   1 june supergroup       1240 2012-12-26 17:58 /tmp/result/20121214/part-00001
-- 建表
create EXTERNAL table IF NOT EXISTS test (userid string) partitioned by (ptDate string) ROW FORMAT DELIMITED FIELDS TERMINATED BY 't';
-- 建立分割槽表,利用分割槽表的特性載入多個目錄下的檔案,並且分割槽欄位可以作為where條件,更為重要的是
-- 這種載入資料的方式是不會移動資料檔案的,這點和 load data 不同,後者會移動資料檔案至資料倉庫目錄。
alter table test add partition (ptDate='20121214') location '/tmp/result/20121214';
-- 注意目錄20121214最後不要畫蛇添足加 /*,我就是linux shell用多了,加了這玩意,除錯了一下午。。。

注意:location後面跟的是目錄,不是檔案,hive會把整個目錄下的檔案都載入到表中:

create EXTERNAL table IF NOT EXISTS userInfo (id int,sex string, age int, name string, email string,sd string, ed string)  ROW FORMAT DELIMITED FIELDS TERMINATED BY 't' location '/hive/dw';

否則,會報錯誤:

FAILED: Error in metadata: MetaException(message:Got exception: org.apache.hadoop.ipc.RemoteException java.io.FileNotFoundException: Parent path is not a directory: /hive/dw/record_2013-04-04.txt

最後提下還有一種方式是建表的時候就指定外部表的資料來源路徑,

但這樣的壞處是隻能載入一個數據源了:

CREATE EXTERNAL TABLE sunwg_test09(id INT, name string) ROW FORMAT DELIMITED FIELDS TERMINATED BY ‘t’ LOCATION ‘/sunwg/test08′; 上面的語句建立了一張名字為sunwg_test09的外表,該表有id和name兩個欄位, 欄位的分割符為tab,檔案的資料資料夾為/sunwg/test08 select * from sunwg_test09; 可以查詢到sunwg_test09中的資料。 在當前使用者hive的根目錄下找不到sunwg_test09資料夾。 此時hive將該表的資料檔案資訊儲存到metadata資料庫中。 mysql> select * from TBLS where TBL_NAME=’sunwg_test09′; 可以看到該表的型別為EXTERNAL_TABLE。 mysql> select * from SDS where SD_ID=TBL_ID; 在表SDS中記錄了表sunwg_test09的資料檔案路徑為hdfs://hadoop00:9000/hjl/test08。 # hjl為hive的資料庫名 實際上外表不光可以指定hdfs的目錄,本地的目錄也是可以的。 比如: CREATE EXTERNAL TABLE test10(id INT, name string) ROW FORMAT DELIMITED FIELDS TERMINATED BY ‘t’

LOCATION ‘file:////home/hjl/sunwg/’;

推薦閱讀:

hive中partition如何使用 http://p-x1984.iteye.com/blog/1156408 用正則表示式匹配w3c日誌,匯入hive http://essen.iteye.com/blog/1720491 hive中的外表EXTERNAL TABLE

http://www.oratea.net/?p=489

HIVE 資料定義 DDL

http://www.kaixinwenda.com/article-iquicksandi-8522691.html