hive使用動態分割槽插入資料詳解
往hive分割槽表中插入資料時,如果需要建立的分割槽很多,比如以表中某個欄位進行分割槽儲存,則需要複製貼上修改很多sql去執行,效率低。因為hive是批處理系統,所以hive提供了一個動態分割槽功能,其可以基於查詢引數的位置去推斷分割槽的名稱,從而建立分割槽。
1.建立一個單一欄位分割槽表
2.往表裡裝載資料,並且動態建立分割槽,以city建立動態分割槽
- hive>
- create table dpartition(id int ,name string )
- partitioned by(ct string );
- hive>
- hive.exec.dynamici.partition=true; #開啟動態分割槽,預設是false
- set hive.exec.dynamic.partition.mode=nonstrict; #開啟允許所有分割槽都是動態的,否則必須要有靜態分割槽才能使用。
- insert overwrite table dpartition
- partition(ct)
- select id ,name,city from mytest_tmp2_p;
- 要點:因為dpartition表中只有兩個欄位,所以當我們查詢了三個欄位時(多了city欄位),所以系統預設以最後一個欄位city為分割槽名,因為分割槽表的
- 分割槽欄位預設也是該表中的欄位,且依次排在表中欄位的最後面。所以分割槽需要分割槽的欄位只能放在後面,不能把順序弄錯。如果我們查詢了四個欄位的話,則會報
- 錯,因為該表加上分割槽欄位也才三個。要注意系統是根據查詢欄位的位置推斷分割槽名的,而不是欄位名稱。
- hive>--檢視可知,hive已經完成了以city欄位為分割槽欄位,實現了動態分割槽。
- hive (fdm_sor)> show partitions dpartition;
- partition
- ct=beijing
- ct=beijing1
注意:使用,insert...select 往表中匯入資料時,查詢的欄位個數必須和目標的欄位個數相同,不能多,也不能少,否則會報錯。但是如果欄位的型別不一致的話,則會使用null值填充,不會報錯。而使用load data形式往hive表中裝載資料時,則不會檢查。如果欄位多了則會丟棄,少了則會null值填充。同樣如果欄位型別不一致,也是使用null值填充。
3.多個分割槽欄位時,實現半自動分割槽(部分欄位靜態分割槽,注意靜態分割槽欄位要在動態前面)
4.多個分割槽欄位時,全部實現動態分割槽插入資料
- 1.建立一個只有一個欄位,兩個分割槽欄位的分割槽表
- hive (fdm_sor)> create table ds_parttion(id int )
- > partitioned by (state string ,ct string );
- 2.往該分割槽表半動態分割槽插入資料
- hive>
- set hive.exec.dynamici.partition=true;
- set hive.exec.dynamic.partition.mode=nonstrict;
- insert overwrite table ds_parttion
- partition(state='china',ct) #state分割槽為靜態,ct為動態分割槽,以查詢的city欄位為分割槽名
- select id ,city from mytest_tmp2_p;
- 3.查詢結果顯示:
- hive (fdm_sor)> select * from ds_parttion where state='china'
- > ;
- ds_parttion.id ds_parttion.state ds_parttion.ct
- 4 china beijing
- 3 china beijing
- 2 china beijing
- 1 china beijing
- 4 china beijing1
- 3 china beijing1
- 2 china beijing1
- 1 china beijing1
- hive (fdm_sor)> select * from ds_parttion where state='china' and ct='beijing';
- ds_parttion.id ds_parttion.state ds_parttion.ct
- 4 china beijing
- 3 china beijing
- 2 china beijing
- 1 china beijing
- hive (fdm_sor)> select * from ds_parttion where state='china' and ct='beijing1';
- ds_parttion.id ds_parttion.state ds_parttion.ct
- 4 china beijing1
- 3 china beijing1
- 2 china beijing1
- 1 china beijing1
- Time taken: 0.072 seconds, Fetched: 4 row(s)
- set hive.exec.dynamici.partition=true;
- set hive.exec.dynamic.partition.mode=nonstrict;
- insert overwrite table ds_parttion
- partition(state,ct)
- select id ,country,city from mytest_tmp2_p;
- 注意:欄位的個數和順序不能弄錯。
5.動態分割槽表的屬性
使用動態分割槽表必須配置的引數 :
set hive.exec.dynamic.partition =true(預設false),表示開啟動態分割槽功能 set hive.exec.dynamic.partition.mode = nonstrict(預設strict),表示允許所有分割槽都是動態的,否則必須有靜態分割槽欄位
動態分割槽相關的調優引數:
set hive.exec.max.dynamic.partitions.pernode=100 (預設100,一般可以設定大一點,比如1000)
表示每個maper或reducer可以允許建立的最大動態分割槽個數,預設是100,超出則會報錯。
set hive.exec.max.dynamic.partitions =1000(預設值)
表示一個動態分割槽語句可以建立的最大動態分割槽個數,超出報錯
set hive.exec.max.created.files =10000(預設) 全域性可以建立的最大檔案個數,超出報錯。