1、分桶简介
- 桶是经过对指定列进行哈希计算来实现的,经过哈希值将一个列名下的数据切分为一组桶,并使每一个桶对应于该列名下的一个存储文件
- 对于每个表或者分区,Hive 能够进一步组织成桶,也就是更为细粒度的数据范围划分
- Bucket是对指定列进行hash,而后根据hash值除以桶的个数进行求余,决定该条记录存放在哪一个桶中
2、分桶操做
1. 建立桶表:java
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 ',';
数据先partitioned by (stat_date string),再clustered by (id) sorted by(age) into 2 bucket,先分区再进行分桶ide
2. 设置环境变量:让程序自动分配reduce的数量从而适配相应的bucket数量测试
set hive.enforce.bucketing=true;
3. 插入数据:从临时表导入数据,须要通过MR优化
from student_tmp insert overwrite table student partition(stat_date='2019-10-08') select id,age,name where stat_date='2019-10-07' sort by age;
4. 查看文件目录:spa
hive> dfs -ls /user/hive/warehouse/student1/stat_date=2019-10-08; 两个目录: /user/hive/warehouse/student1/stat_date=2019-10-08/000000_0 /user/hive/warehouse/student1/stat_date=2019-10-08/000001_0
5. 查看 sampling 数据code
hive> select * from student1 > TableSample(bucket 1 out of 2 on id);
这里指的是查询 2/2 = 1个bucket数据,从第1个bucket开始orm
tablesample是抽样语句,语法:TABLESAMPLE(BUCKET x OUT OF y)开发
- x表示从哪一个bucket开始抽取
- y表示抽样的比例,桶数/y
例如:桶数64,tablesample(bucket 3 out of 32)
总共抽取(64/32=)2个bucket的数据,分别为第3个bucket和第(3+32=)35个bucket的数据string
3、分桶的优缺点
- 分桶取样更高效,由于在处理大规模的数据集时,在开发、测试阶段将全部的数据所有处理一遍可能不太现实,若是一个表已经对某一列制做了bucket,就能够采样全部桶中指定序号的某个桶,这就减小了访问量
- 为了得到更好的查询处理效率, 桶为了表提供了额外的结构,Hive在处理某些查询时利用这个结构,能给有效地提升查询效率
- 链接两个在相同列上划分了桶的表,可使用 Map-side Join 的高效实现,优化join操做(下一篇笔记会讲)
- 缺点:使用业务字段来查询的话,没有什么效果