Hive如何根據表中某個字段動態分區


使用hive儲存數據時,需要對做分區,如果從kafka接收數據,將每天的數據保存一個分區(按天分區),保存分區時需要根據某個字段做動態分區,而不是傻傻的將數據寫到某一個臨時目錄最后倒入到某一個分區,這是靜態分區。

 

Hive動態分區步驟如下:

1、建立某一個源表模擬數據源並插入一些數據

create table t_test_p_source (
    id string,
    name string,
    birthday string
) 
row format delimited fields terminated by '\t'
stored as textfile;

insert into t_test_p_source values ('a1', 'zhangsan', '2018-01-01');
insert into t_test_p_source values ('a2', 'lisi', '2018-01-02');
insert into t_test_p_source values ('a3', 'zhangsan', '2018-01-03');
insert into t_test_p_source values ('a4', 'wangwu', '2018-01-04');
insert into t_test_p_source values ('a5', 'sanzang', '2018-01-05');
insert into t_test_p_source values ('a6', 'zhangsan2', '2018-01-01');

 

2、建立一張分區表 (按ds字段分區)

create table t_test_p_target (
    id string,
    name string
)
partitioned by (ds string)
row format delimited fields terminated by '\t'
stored as textfile;

 

3、向分區表中插入數據

SET hive.exec.dynamic.partition=true;   #是否開啟動態分區,默認是false,所以必須要設置成true
SET hive.exec.dynamic.partition.mode=nonstrict;    # 動態分區模式,默認為strict, 表示表中必須一個分區為靜態分區,nostrict表示允許所有字段都可以作為動態分區

insert into table t_test_p_target partition (ds) select id, name, birthday as ds from t_test_p_source;

 

4、測試是否動態分區了

 2018-01-01這個分區只有2條數據,再來看下HDFS上的分區目錄

 

至此,hive動態分區已經完成了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM