hive中table可以拆分成partition,table和partition可以通過‘CLUSTERED BY ’進一步分bucket,bucket中的數據可以通過‘SORT BY’排序。
bucket主要作用:
1. 數據sampling
2. 提升某些查詢操作效率,例如mapside join
需要特別注意的是:clustered by和sorted by不會影響數據的導入,這意味着,用戶必須自己負責數據如何如何導入,包括數據的分桶和排序。
'set hive.enforce.bucketing = true' 可以自動控制上一輪reduce的數量從而適配bucket的個數,當然,用戶也可以自主設置mapred.reduce.tasks去適配bucket 個數,推薦使用'set hive.enforce.bucketing = true'
示例:
建臨時表student_tmp,並導入數據:
hive> desc student_tmp;
OK
id int
age int
name string
stat_date string
Time taken: 0.106 seconds
hive> select * from student_tmp;
OK
1 20 zxm 20120801
2 21 ljz 20120801
3 19 cds 20120801
4 18 mac 20120801
5 22 android 20120801
6 23 symbian 20120801
7 25 wp 20120801
Time taken: 0.123 seconds
建student表:
hive>create table student(id INT, age INT, name STRING)
>partitioned by(stat_date STRING)
>clustered by(id) sorted by(age) into 2 bucket
>row format delimited fields terminated by ',';
設置環境變量:
>set hive.enforce.bucketing = true;
插入數據:
>from student_tmp
>insert overwrite table student partition(stat_date="20120802")
>select id,age,name where stat_date="20120801" sort by age;
查看文件目錄:
$ hadoop fs -ls /user/hive/warehouse/studentstat_date=20120802/
Found 2 items
-rw-r--r-- 1 work supergroup 31 2012-07-31 19:52 /user/hive/warehouse/student/stat_date=20120802/000000_0
-rw-r--r-- 1 work supergroup 39 2012-07-31 19:52 /user/hive/warehouse/student/stat_date=20120802/000001_0
查看sampling數據:
hive> select * from student tablesample(bucket 1 out of 2 on id);
Total MapReduce jobs = 1
Launching Job 1 out of 1
.......
OK
4 18 mac 20120802
2 21 ljz 20120802
6 23 symbian 20120802
Time taken: 20.608 seconds
tablesample是抽樣語句,語法:TABLESAMPLE(BUCKET x OUT OF y)
y必須是table總bucket數的倍數或者因子。hive根據y的大小,決定抽樣的比例。例如,table總共分了64份,當y=32時,抽取 (64/32=)2個bucket的數據,當y=128時,抽取(64/128=)1/2個bucket的數據。x表示從哪個bucket開始抽取。例 如,table總bucket數為32,tablesample(bucket 3 out of 16),表示總共抽取(32/16=)2個bucket的數據,分別為第3個bucket和第(3+16=)19個bucket的數據。
reference:
Working with bucketed tables
Data manipulation statements