1. 概念
- 分桶表也叫做桶表,是一种用于优化查询而设计的表类型。
- 分桶表对应的数据文件在底层会被分解为若干个部分(拆分成若干个独立的小文件)
- 在分同时,要指定根据哪个字段将数据分为几个桶(几个部分)
2. 规则
桶编号相同的数据会被分到同一个桶当中,hash_function取决于分桶字段bucketing_column的类型,如果bucketing_cloumn类型是复杂类型或则String,则将使用该类型派生的某个数字比如:hashcode。
Bucket number = hash_function(bucketing_column) mod num_buckets
//分桶编号 = 哈希方法(分桶字段) 取模 分桶个数
标准建表语法树中,分桶的字段必须是表中已经存在的字段。
//结构
[clustered by(col_name,col_name,...)[sorted by (col_name[ASC|DESC],...)] into num_buckets buckets]
//案例
create table Fentong_tablename(
count_date string,
country string,
state string,
fips int,
cases int,
deaths int)
clustered by(state)
sorted by (cases desc) into 5 buckets;
3. 分桶表数据加载
# 1. 开启分桶的功能,从Hive2.0开始不再需要设置
set hive.enforce.bucketing=true;
# 2. 把数据源加载到普通hive表中
drop table if exists Putong_tablename;
create table Putong_tablename(
count_date string,
country string,
state string,
fips int,
cases int,
deaths int)
row format delimited fields terminated by ",";
# 3. 将数据源上传到HDFS,表名对应的路径下
hadoop fs -put us-covid19-counties.dat
/user/hive/warehouse/dbname.db/Putong_tablename
# 4. 使用insert+select语法将数据从普通表加载到分桶表中
insert into Fentong_tablename select * from Putong_tablename;
4. 分桶表使用好处
- 基于分桶字段查询时,减少全表扫描
- JOIN时可以提高MR程序效率,减少笛卡尔积数量
- 分桶表数据进行高校抽样