分區的主要作用是可用允許我們只統計一部分內容,加快統計的速度。
什麼是分桶
假如我們有個表t_buck。
create table t_buck(id string,name string)
clustered by (id) sort by(id) into 4 buckets;
指定了根據id分成4個桶。
只是說明了表會分桶,具體的分區需要在導入數據時產生。最好的導入數據方式是insert into table;
開始的時候我們的數據都是在一起的,按照上面的分桶結果,會在表目錄下產生多個文件:/user/hive/warehouse/test_db/t_buk/
000001_0
000002_0
000003_0
000004_0
每個文件中的內容是根據HASH散列後得到的結果。
實驗
使用下面的代碼創建表:
create table t_p(id string,name string)
row format delimited fields terminated by ',';
load data local inpath '/root/buck.data' overwrite into table t_p;
create table t_buck(id string,name string)
clustered by(id) sorted by(id)
into 4 buckets
row format delimited fields terminated by ',';
# 要開啓模式開關
set hive.enforce.bucketing = true;
set mapreduce.job.reduces=4;
# 查詢時cluster by指定的字段就是partition時分區的key
# 每個區中的數據根據id排序。
insert into table t_buck
select * from t_p cluster by(id);
來看一下sort by的結果。
set mapreduce.job.reduces=4;
select * from t_p sort by id;
輸出結果爲:
+---------+-----------+--+
| t_p.id | t_p.name |
+---------+-----------+--+
| 12 | 12 |
| 13 | 13 |
| 4 | 4 |
| 8 | 8 |
| 14 | 14 |
| 2 | 2 |
| 6 | 6 |
| 1 | 1 |
| 10 | 10 |
| 11 | 11 |
| 3 | 3 |
| 5 | 5 |
| 7 | 7 |
| 9 | 9 |
+---------+-----------+--+
明顯看出是每個Reduce中有序而不是全局有序。
cluster by(id) = distribute by(id) sort by(id)
distribute by(id)指定分發字段,sort by指定排序字段。
分桶的作用
觀察下面的語句。
select a.id,a.name,b.addr from a join b on a.id = b.id;
如果a表和b表已經是分桶表,而且分桶的字段是id字段,那麼做這個操作的時候就不需要再進行全表笛卡爾積了。但是如果標註了分桶但是實際上數據並沒有分桶,那麼結果就會出問題。