分区提供一个隔离数据和优化查询的便利方式。不过,并非所有的数据集都可形成合理的分区。对于一张表或者分区,Hive 可以进一步组织成桶,也就是更为细粒度的数据范围划分。
分桶是将数据集分解成更容易管理的若干部分的另一个技术。
分区针对的是数据的存储路径;分桶针对的是数据文件。
(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)创建分桶表
- hive (hive3)> create table stu_buck(id int , name string) clustered by(id) into 4 buckets row format delimited fields terminated by '';
- OK
- Time taken: 0.671 seconds
(4)导入数据到分桶表中,load 的方式
hive (hive3)> load data local inpath '/home/atguigu/hive/student.txt' into table stu_buck;
(5)查看创建的分桶表中是否分成4 个桶

(6)查询分桶的数据
- hive (hive3)> select * from stu_buck;
- OK
- stu_buck.id stu_buck.name
- 1001 zzz
- 1002 ddd
- 1111 ccc
- Time taken: 0.549 seconds, Fetched: 3 row(s)
(7)分桶规则:
根据结果可知:Hive 的分桶采用对分桶字段的值进行哈希,然后除以桶的个数求余的方式决定该条记录存放在哪个桶当中
(1)reduce 的个数设置为-1,让 Job 自行决定需要用多少个 reduce 或者将 reduce 的个数设置为大于等于分桶表的桶数。
(2)从 hdfs 中 load 数据到分桶表中,避免本地文件找不到问题。
(3)不要使用本地模式。
hive(default)>insert into table stu_buck select * from student_insert;