1. 程式人生 > 實用技巧 >hive分桶表的學習

hive分桶表的學習

前言:

每一個表或者分割槽,hive都可以進一步組織成桶,桶是更細粒度的資料劃分,他本質不會改變表或分割槽的目錄組織方式,他會改變資料在檔案中的分佈方式。

分桶規則:對分桶欄位值進行雜湊,雜湊值除以桶的個數求餘,餘數決定了該條記錄在哪個桶中,也就是餘數相同的在一個桶中。
  
桶為表加上額外結構,連結相同列劃分了桶的表,可以使用map-side join更加高效。
優點:1、提高join查詢效率 2、提高抽樣效率

1、建表

通過 clustered by(欄位名) into bucket_num buckets 分桶,意思是根據欄位名分成bucket_num個桶

create table
test_bucket ( id int comment 'ID', name string comment '名字' ) comment '測試分桶' clustered by(id) into 4 buckets ROW FORMAT DELIMITED FIELDS TERMINATED BY ',';

2、插入資料

2.1 資料

buckt_data.txt

1,name1
2,name2
3,name3
4,name4
5,name5
6,name6
7,name7
8,name8
9,name9

2.2 load data

直接load data不會有分桶的效果,這樣和不分桶一樣,在HDFS上只有一個檔案。

load data local inpath '/opt/test/buckt_data.txt' into table test_bucket;

需要藉助中間表

create table text_bucket_test (
id int comment 'ID', 
name string comment '名字'
)
comment '測試分桶中間表'
ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' ;

先將資料load到中間表

load data local inpath '/opt/test/buckt_data.txt' into table text_bucket_test;

然後通過下面的語句,將中間表的資料插入到分桶表中,這樣會產生四個檔案。

insert into test_bucket select * from text_bucket_test;

然後我們檢視分桶表的資料目錄,發現好像也只有一個檔案,並沒有按之前的4個檔案,也就是4個桶這樣來劃分。

分桶也就是分割槽,分割槽數量等於檔案數,所以上面方法並沒有分桶。

所以需要開啟強制分桶:

set hive.enforce.bucketing = true;   開啟強制分桶

重新匯入資料:

insert into  test_bucket  select *  from text_bucket_test;

發現組織檔案的有變化:

3.1 檢視結果

用sql看和用hadoop命令看每個檔案,結果每個桶內都是按id升序排序的,也就是和最開始的截圖是一樣的

3.2 好處

因為每個桶內的資料是排序的,這樣每個桶進行連線時就變成了高效的歸併排序