Hive中分割槽表及陷阱
分割槽表
分割槽表實際就是對應hdfs檔案系統上的的獨立的資料夾,該檔案是夾下是該分割槽所有資料檔案。
分割槽可以理解為分類,通過分類把不同型別的資料放到不同的目錄下。
分類的標準就是分割槽欄位,可以一個,也可以多個。
分割槽表的意義在於優化查詢。查詢時儘量利用分割槽欄位。如果不使用分割槽欄位,就會全部掃描。
在查詢是通過where子句查詢來指定所需的分割槽。
樣例
create external table if not exists emp_partition(
empno int,
ename string,
job string,
mgr int,
hiredate string,
sal double,
comm double,
deptno int
)
partitioned by (month string)
row format delimited fields terminated by '\t'
操作步驟
建立分割槽表
create external table if not exists emp_partition(
empno int,
ename string,
job string,
mgr int,
hiredate string,
sal double,
comm double,
deptno int
)
partitioned by (month string)
row format delimited fields terminated by '\t'
還可以新增二級分割槽
partitioned by (month string,day string):相當於建立2個資料夾,在month下建立了day資料夾
day檔案下就是具體的檔案。
載入資料到指定分割槽
load data local inpath '/opt/datas/emp.txt' into table default.emp_partition partition (month='201803');
load data local inpath '/opt/datas/emp.txt' into table **default.emp_partition partition (month='201804');
分割槽其實就是資料夾名稱。分割槽表就是資料夾。分割槽相當於對檔案坐了分類,根據分類拆分不同的檔案。
分割槽中的資料查詢
查詢201803分割槽資料
命令:select * from emp_partition where month='201803' ;
查詢201803分割槽資料
命令:select * from emp_partition where month='201804' ;
201803分割槽與201804分割槽組合統計總人數
編寫sql檔案
sql內容
select count(ename) from emp_partition where month='201803' union all select count(ename) from emp_partition where month='201804'
執行sql檔案
bin/hive -f /opt/datas/emp_partition.sql
分割槽陷阱
建立分割槽表
create table dept_partition(
deptno int,
dname string,
loc string
)
partitioned by (day string)
row format delimited fields terminated by '\t';
在分割槽表下建立分割槽資料夾。
建立分割槽目錄:
dfs -mkdir /user/hive/warehouse/dept_partition/day=20180306
把資料檔案上傳到分割槽資料夾下
通過 dfs -put /本地檔案 /hdfs目錄 ,完成檔案上傳。
dfs -put /opt/datas/dept.txt /user/hive/warehouse/dept_partition/day=20180306;
查詢資料沒有結果
select * from dept_partition ;
原因 mysql下的matehouse下的分割槽表中沒有分割槽資料
解決方法1
msck repair table dept
說明:users can run a metastore check command with the repair table option
msck的意思就是matestore check的意思
解決方法2
alter table dept_partition add partition(day='20180306');
測試結果
select * from dept_partition;
為什麼會出現這樣的問題。
因為通過HDFS put/cp命令往表目錄下拷貝分割槽目錄資料檔案時並沒有在metastore中建立分割槽資料。所以即使你把資料copy、put到資料夾下也不會查詢到。