尚硅谷大数据技术之Hive(新)第6章 查询

6.6 分桶及抽样查询

6.6.1 分桶表数据存储

分区针对的是数据的存储路径;分桶针对的是数据文件。

分区提供一个隔离数据和优化查询的便利方式。不过,并非所有的数据集都可形成合理的分区,特别是之前所提到过的要确定合适的划分大小这个疑虑。

分桶是将数据集分解成更容易管理的若干部分的另一个技术。

1.先创建分桶表,通过直接导入数据文件的方式

(1)数据准备

1001 ss1
1002 ss2
1003 ss3
1004 ss4
1005 ss5
1006 ss6
1007 ss7
1008 ss8
1009 ss9
1010 ss10
1011 ss11
1012 ss12
1013 ss13
1014 ss14
1015 ss15
1016 ss16

(2)创建分桶表

create table stu_buck(id int, name string)

clustered by(id)

into 4 buckets

row format delimited fields terminated by '\t';

(3)查看表结构

hive (default)> desc formatted stu_buck;

Num Buckets:            4     

(4)导入数据到分桶表中

hive (default)> load data local inpath '/opt/module/datas/student.txt' into table

 stu_buck;

(5)查看创建的分桶表中是否分成4个桶,如图6-7所示

发现并没有分成4个桶。是什么原因呢?

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

(1)先建一个普通的stu表

create table stu(id int, name string)

row format delimited fields terminated by '\t';

(2)向普通的stu表中导入数据

load data local inpath '/opt/module/datas/student.txt' into table stu;

(3)清空stu_buck表中数据

truncate table stu_buck;

select * from stu_buck;

(4)导入数据到分桶表,通过子查询的方式

insert into table stu_buck

select id, name from stu;

(5)发现还是只有一个分桶,如图6-8所示

图6-8 未分桶

(6)需要设置一个属性

hive (default)> set hive.enforce.bucketing=true;

hive (default)> set mapreduce.job.reduces=-1;

hive (default)> insert into table stu_buck

select id, name from stu;

图6-9 分桶

(7)查询分桶的数据

hive (default)> select * from stu_buck;

OK

stu_buck.id     stu_buck.name

1004    ss4

1008    ss8

1012    ss12

1016    ss16

1001    ss1

1005    ss5

1009    ss9

1013    ss13

1002    ss2

1006    ss6

1010    ss10

1014    ss14

1003    ss3

1007    ss7

1011    ss11

1015    ss15