套話之分桶的定義:
分桶表是對列值取哈希值的方式,将不同資料放到不同檔案中存儲。對于 hive 中每一個表、分區都可以進一步進行分桶。
列的哈希值除以桶的個數來決定每條資料劃分在哪個桶中。(網上其它定義更詳細,有點繞,結合後面執行個體)
适用場景:資料抽樣( sampling )、map-join
幹貨之分桶怎麼分:
1.開啟支援分桶
set hive.enforce.bucketing=true;
預設:false;設定為 true 之後,mr 運作時會根據 bucket 的個數自動配置設定 reduce task 個數。
(使用者也可以通過 mapred.reduce.tasks 自己設定 reduce 任務個數,但分桶時不推薦使用)
注意:一次作業産生的桶(檔案數量)和 reduce task 個數一緻。
2.往分桶表中加載資料
insert into table bucket_table select columns from tbl;
insert overwrite table bucket_table select columns from tbl;
3.桶表 抽樣
select * from bucket_table tablesample(bucket 1 out of 4 on columns);
TABLESAMPLE 文法:
TABLESAMPLE(BUCKET x OUT OF y)
x:表示從哪個 bucket 開始抽取資料
y:必須為該表總 bucket 數的倍數或因子
4.分桶執行個體(詳解)
具體如下:
1.啟動hive(遠端一體化模式):①service iptables stop // ② service mysqld start // ③hive ---service metastore //④ hive(老套路)
2.準備:在node03節點的root/hivedata目錄下 建立一個資料檔案ft
①vim ft

1 zhang 12
2 lisi 34
3 wange 23
4 zhouyu 15
5 guoji 45
6 xiafen 48
7 yanggu 78
8 liuwu 41
9 zhuto 66
10 madan 71
11 sichua 89

注意:這裡的資料間是用制表符'\t'來分隔的,後面在建表的時候要注意 terminated by '\t'; 不然導入表中的資料因為格式不符出現'null'
②在資料庫heh.db中建表:

hive> CREATE TABLE ft( id INT, name STRING, age INT)
> ROW FORMAT DELIMITED FIELDS TERMINATED BY'\t';
OK
Time taken: 0.216 seconds
hive> load data local inpath'/root/hivedata/ft' into table ft;
Loading data to table hehe.ft
Table hehe.ft stats: [numFiles=1, totalSize=127]
OK
Time taken: 1.105 seconds
hive> select *from ft;
OK
1 zhang 12
2 lisi 34
3 wange 23
4 zhouyu 15
5 guoji 45
6 xiafen 48
7 yanggu 78
8 liuwu 41
9 zhuto 66
10 madan 71
11 sichua 89
NULL NULL NULL
Time taken: 0.229 seconds, Fetched: 12 row(s)

再建立一張分桶表fentong并把ft的資料插入到fentong:

hive> create table fentong(
> id int,
> name string,
> age int,)clustered by(age) into 4 buckets
> row format delimited fields terminated by ',';
建立一張表:它以字段age來劃分成4個桶
插入資料:
hive> insert into table fentong select name,age from ft;
ok! 現在分桶表中出現之前建立的資料:select * from fentong

③執行抽樣: select id, name, age from fentong tablesample(bucket 1 out of 4 on age);
網上很多案例教程說的非常繞,一時很難離清楚,現分享如下通俗 易懂的教程:
怎麼分:①在前面建立分桶表的時候有這樣語句:age int,)clustered by(age) into 4 buckets 說明本案例是以年齡age來劃分成4個桶;
分桶的資料怎麼分到四個桶:它是将表中對應的字段值(比如age)分别來除以桶的個數4,結果取餘數(也就是取模),若餘數為0就放到1号桶,餘數為1就放到2号桶
餘數為2就放到3号桶,餘數為3就放到4号桶
②這句話怎麼了解:select id, name, age from psnbucket tablesample(bucket 2 out of 4 on age);
它是說:将你的資料劃分成4個桶,取四個桶中的第一個桶的資料
③運作程式

hive> select id, name, age from fentong tablesample(bucket 1 out of 4 on age);
OK
NULL NULL NULL
6 xiafen 48
1 zhang 12
hive> select id, name, age from fentong tablesample(bucket 2 out of 4 on age);
OK
11 sichua 89
8 liuwu 41
5 guoji 45
hive> select id, name, age from fentong tablesample(bucket 3 out of 4 on age);
OK
9 zhuto 66
7 yanggu 78
2 lisi 34

④推算過程: