hive bucket

来源:互联网 发布:linux tmp空间清理 编辑:程序博客网 时间:2024/04/29 05:51

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的数据。

原创粉丝点击