hive建立表 內部表和外部表)

2021-10-17 11:16:15 字數 3022 閱讀 2973

1)建表語法

create [external] table [if not exists] table_name

[(col_name data_type [comment col_comment], ...)]

[comment table_comment]

[partitioned by (col_name data_type [comment col_comment], ...)]

[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]

2)字段解釋說明:

(1)create table 建立乙個指定名字的表。如果相同名字的表已經存在,則丟擲異常;使用者可以用 if not exists 選項來忽略這個異常。

(2)external關鍵字可以讓使用者建立乙個外部表,在建表的同時指定乙個指向實際資料的路徑(location),hive建立內部表時,會將資料移動到資料倉儲指向的路徑;若建立外部表,僅記錄資料所在的路徑,不對資料的位置做任何改變。在刪除表的時候,內部表的元資料和資料會被一起刪除,而外部表只刪除元資料,不刪除資料。

(3)comment:為表和列新增注釋。

(4)partitioned by建立分割槽表

(5)clustered by建立分桶表

(6)sorted by不常用

(7)row format

delimited [fields terminated by char] [collection items terminated by char]

[map keys terminated by char] [lines terminated by char]

| serde serde_name [with serdeproperties (property_name=property_value, property_name=property_value, ...)]

使用者在建表的時候可以自定義serde或者使用自帶的serde。如果沒有指定row format 或者row format delimited,將會使用自帶的serde。在建表的時候,使用者還需要為表指定列,使用者在指定表的列的同時也會指定自定義的serde,hive通過serde確定表的具體的列的資料。

(8)stored as指定儲存檔案型別

常用的儲存檔案型別:sequencefile(二進位制序列檔案)、textfile(文字)、rcfile(列式儲存格式檔案)

如果檔案資料是純文字,可以使用stored as textfile。如果資料需要壓縮,使用 stored as sequencefile。

(9)location :指定表在hdfs上的儲存位置。

(10)like允許使用者複製現有的表結構,但是不複製資料。

1)理論

預設建立的表都是所謂的管理表,有時也被稱為內部表。因為這種表,hive會(或多或少地)控制著資料的生命週期。hive預設情況下會將這些表的資料儲存在由配置項hive.metastore.warehouse.dir(例如,/user/hive/warehouse)所定義的目錄的子目錄下。 當我們刪除乙個管理表時,hive也會刪除這個表中資料。管理表不適合和其他工具共享資料。

案例實操

(1)普通建立表

create table if not exists student2(

id int, name string

) row format delimited fields terminated by '\t'

stored as textfile

location '/user/hive/warehouse/student2';

(2)根據查詢結果建立表(查詢的結果會新增到新建立的表中)

create table if not exists student3

as select id, name from student;

(3)根據已經存在的表結構建立表

create table if not exists student4

like

student;

(4)查詢表的型別

hive (default)> desc formatted student2;

table type:             managed_table  

2)管理表和外部表的使用場景:(原始資料(公共部門的共享資料)要建成外部表,這樣不會被破壞,在原始資料的基礎上通過選取建立內部表(管理表),在本部門內的資料表上可以刪除)

3)案例實操

分別建立部門和員工外部表,並向表中匯入資料。

(1)原始資料

dept.txt

emp.txt

(2)建表語句

建立部門表

建立員工表

(3)檢視建立的表

(4)向外部表中匯入資料

匯入資料

查詢結果

(5)檢視**式化資料

hive外部表和內部表

1.內部表指hive建立並通過load data inpath進資料庫的表,這種表可以理解為資料和表結構都儲存在一起的資料表。當你通過drop table table name 刪除元資料中表結構的同時,表中的資料也同樣會從hdfs中被刪除。sql view plain copy create ta...

Hive內部表和外部表

總結一下hive的內部表和外部表以及兩者的區別。平時建立的普通表為內部表 create table test internal id string comment id name string comment 名字 comment 測試內部表 row format delimited fields ...

Hive 外部表和內部表

外部表說明 外部表因為是指定其他的hdfs路徑的資料載入到表當中來,所以hive表會認為自己不完全獨佔這份資料,所以刪除hive表的時候,資料仍然存放在hdfs當中,不會刪掉 管理表和外部表的使用場景 操作案例 分別建立老師與學生表外部表,並向表中載入資料 建立老師表 create external...