分桶练习
1. 为什么分桶
在理解了分区后,我们用对分区的理解去理解分桶,分区是对于一个超大的数据进行按一定方法风区放置,表现在HDFS上的现象就是建立多个文件夹来划分数据。在查询指定一个范围内数据时不需要对整个文件进行读取,而是对相对少量的文件夹进行读取就可。
但在分区中,单单一个分区也会有大量的数据存在,其表示为一个文件夹内有极大单个文件,也会导致查询速度变慢,为了解决这一问题就需要使用到分桶
2. 什么是分桶
分桶就是在HDFS文件等级上对数据进行切分存储,将一个数据文件进行切分(同一文件夹中)存放。
未分桶的表,文件结构
分桶后的表,文件结构
3. 如何使用分桶
1)创建表
注意:partitioned要写在 分桶之前
create table stu_buck(
id int,
name string
)
partitioned by (month string)
clustered by(id) into 4 buckets
row format delimited fields terminated by '\t';
2)导入数据
分桶的数据直接使用load导入是不行的,要使用insert导入才会进行分桶
-- 创建一个一样字段的表没有分桶的表stu
create table stu(
id int,
name string
)
partitioned by (month string)
row format delimited fields terminated by '\t';
-- 导入数据
load data local inpath '/opt/test/student-201907.txt' into table stu partition (month="201907");
load data local inpath '/opt/test/student-201908.txt' into table stu partition (month="201908");
--在导入数据之前还要设置一步,(必须步),虽然默认为-1但还是会运行错误
set hive.enforce.bucketing=true;
set mapreduce.job.reduces=-1;
-- 在将数据导入到stu_buck
insert into table stu_buck partition(month="201907") select id, name from stu where month="201907";
insert into table stu_buck partition(month="201908") select id, name from stu where month="201908";
-- 或者
insert into table stu_buck select id,name,month from stu;
**3)分桶的一些特殊操作,分桶抽样查询 **
对于非常大的数据集,有时用户需要使用的是一个具有代表性的查询结果而不是全部结果。Hive可以通过对表进行抽样来满足这个需求。
查询表stu_buck中的数据。
select * from stu_buck tablesample(bucket 1 out of 4 on id) where month="201907";
注:tablesample是抽样语句,语法:TABLESAMPLE(BUCKET x OUT OF y) 。
y必须是table总bucket数的倍数或者因子。hive根据y的大小,决定抽样的比例。
例如,table总共分了4份,当y=2时,抽取(4/2=)2个bucket的数据,当y=8时,抽取(4/8=)1/2个bucket的数据。
x表示从哪个bucket开始抽取。
例如,table总bucket数为4,tablesample(bucket 4 out of 4),表示总共抽取(4/4=)1个bucket的数据,抽取第4个bucket的数据。
注意:x的值必须小于等于y的值,否则
FAILED: SemanticException [Error 10061]: Numerator should not be bigger than denominator in sample clause for table stu_buck