Hive的表结构之分桶表

一、分桶表(Bucket Table)

  对数据进行hash取值, 然后放到不同的文件中存储。 注意: 是hash.

  抽样(sampling)可以在全体数据上进行采样,这样效率自然就低,它还是要去访问所有数据。而如果一个表已经对某一列制作了bucket,就可以采样所有桶中指定序号的某个桶,这就减少了访问量。’

桶表功能:

  • 1)数据抽样

  • 2)提升某些查询操作效率,如:mapside join

容易和分区表混淆。

  • 分区针对的是数据的存储路径(目录);分桶针对的是数据文件
    这里写图片描述

二、分桶表插入数据

2.1、直接插入

-- 创建分桶表
create table bucket_table(
id int,
name string,
age int) clustered by(name) into 5 buckets;

--  插入数据
 insert into table  bucket_table values(1,'chb', 18), (2,'ling', 18),(3,'za', 89), (4,'lisi',50), (5, 'w5', 47);
 

2.2、通过load data加载数据

-- 创建分桶表
create table stu_buck(id int, name string)
clustered by(id) 
into 4 buckets
row format delimited fields terminated by '\t';


-- 加载数据
load data local inpath '/uardata1/hivetest/student' into table stu_buck;



### 注意: 数据没有分文件
### 注意: 数据没有分文件
### 注意: 数据没有分文件
发现并没有分成4个桶。是什么原因呢?
-rwxrwxrwt   3 root hive         13 2020-07-23 22:39 hdfs://chb1:8020/user/hive/warehouse/hivetest.db/stu_buck/student

2.3、创建分桶表时,数据通过子查询的方式导入

1)先建一个普通的stu表
	create table stu(id int, name string) row format delimited fields terminated by '\t';2)向普通的stu表中导入数据
	load data local inpath '/uardata1/hivetest/student' into table stu;3)清空stu_buck表中数据
	truncate table stu_buck;4)导入数据到分桶表,通过子查询的方式
	insert into table stu_buck select id, name from stu;

(5) 如果还不分桶, 需要设置下面属性属性
    -- 开启分桶功能
	hive (default)> set hive.enforce.bucketing=true;
	 -- 设置-1,会根据桶的数量设置reduce的个数
	hive (default)> set mapreduce.job.reduces=-1;
	hive (default)> insert into table stu_buck select id, name from stu;

三、分桶抽样查询

  对于非常大的数据集,有时用户需要使用的是一个具有代表性的查询结果而不是全部结果。Hive可以通过对表进行抽样来满足这个需求。
查询表stu_buck中的数据。

hive (default)> select * from stu_buck tablesample(bucket 1 out of 4 on id);

注: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开始抽取,如果需要取多个分区,以后的分区号为当前分区号加上y。例如,table总bucket数为4,tablesample(bucket 1 out of 2),表示总共抽取(4/2=)2个bucket的数据,抽取第1(x)个和第3(x+y)个bucket的数据。

注意:x的值必须小于等于y的值,否则FAILED: SemanticException [Error 10061]: Numerator should not be bigger than denominator in sample clause for table stu_buck

猜你喜欢

转载自blog.csdn.net/wuxintdrh/article/details/107549612