1、分桶表數(shù)據(jù)存儲(chǔ)
概念
分區(qū)針對(duì)的是數(shù)據(jù)的存儲(chǔ)路徑,分桶針對(duì)的是數(shù)據(jù)文件。
分區(qū)提供一個(gè)隔離數(shù)據(jù)和優(yōu)化查詢的便利方式。不過,并非所有的數(shù)據(jù)集都可形成合理的分區(qū),特別是之前所提到過的要確定合適的劃分大小這個(gè)疑慮。
分桶是將數(shù)據(jù)集分解成更容易管理的若干部分的另一個(gè)技術(shù)。
方式一:先創(chuàng)建分桶表,通過直接導(dǎo)入數(shù)據(jù)文件的方式
(1)數(shù)據(jù)準(zhǔn)備
student.txt
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)創(chuàng)建分桶表
hive (default)> create table stu_buck(id int, name string)
clustered by(id)
into 4 buckets
row format delimited fields terminated by '\t';
(3)查看表結(jié)構(gòu)
hive (default)> desc formatted stu_buck;
Num Buckets: 4
(4)導(dǎo)入數(shù)據(jù)到分桶表中
hive (default)> load data local inpath '/opt/module/datas/student.txt' into table stu_buck;
尖叫提示:查看創(chuàng)建的分桶表中是否分成4個(gè)桶,發(fā)現(xiàn)并沒有分成4個(gè)桶。是什么原因呢?我們繼續(xù)方式二。
方式二:創(chuàng)建分桶表時(shí),數(shù)據(jù)通過子查詢的方式導(dǎo)入
(1)先建一個(gè)普通的stu表
hive (default)> create table stu(id int, name string)
row format delimited fields terminated by '\t';
(2)向普通的stu表中導(dǎo)入數(shù)據(jù)
hive (default)> load data local inpath '/opt/module/datas/student.txt' into table stu;
(3)清空stu_buck表中數(shù)據(jù)
hive (default)> truncate table stu_buck;
hive (default)> select * from stu_buck;
(4)導(dǎo)入數(shù)據(jù)到分桶表,通過子查詢的方式
hive (default)> insert into table stu_buck
select id, name from stu cluster by(id);
(5)發(fā)現(xiàn)還是只有一個(gè)分桶,需要設(shè)置一下屬性,再來一遍
hive (default)>set hive.enforce.bucketing=true;
hive (default)> set mapreduce.job.reduces=-1;
hive (default)> truncate table stu_buck;
hive (default)>insert into table stu_buck select id, name from stu cluster by(id);
(6)查詢分桶的數(shù)據(jù)
hive (default)> select * from stu_buck;
OK
stu_buck.id stu_buck.name
1001 ss1
1005 ss5
1009 ss9
1012 ss12
1016 ss16
1002 ss2
1006 ss6
1013 ss13
1003 ss3
1007 ss7
1010 ss10
1014 ss14
1004 ss4
1008 ss8
1011 ss11
1015 ss15
2、分桶抽樣查詢
對(duì)于非常大的數(shù)據(jù)集,有時(shí)用戶需要使用的是一個(gè)具有代表性的查詢結(jié)果而不是全部結(jié)果。Hive可以通過對(duì)表進(jìn)行抽樣來滿足這個(gè)需求。
查詢表stu_buck中的數(shù)據(jù)
hive (default)> select * from stu_buck tablesample(bucket 1 out of 4 on id);
尖叫提示:tablesample是抽樣語句,語法:TABLESAMPLE(BUCKET x OUT OF y) 。
y必須是table總bucket數(shù)的倍數(shù)或者因子。hive根據(jù)y的大小,決定抽樣的比例。例如,table總共分了4份,當(dāng)y=2時(shí),抽取(4/2=)2個(gè)bucket的數(shù)據(jù),當(dāng)y=8時(shí),抽取(4/8=)1/2個(gè)bucket的數(shù)據(jù)。
x表示從哪個(gè)bucket開始抽取。例如,table總bucket數(shù)為4,tablesample(bucket 4 out of 4),表示總共抽?。?/4=)1個(gè)bucket的數(shù)據(jù),抽取第4個(gè)bucket的數(shù)據(jù)。
注意:x的值必須小于等于y的值,否則
FAILED: SemanticException [Error 10061]:
Numerator should not be bigger than denominator in sample clause for table stu_buck
3、數(shù)據(jù)塊抽樣
Hive提供了另外一種按照百分比進(jìn)行抽樣的方式,這種是基于行數(shù)的,按照輸入路徑下的數(shù)據(jù)塊百分比進(jìn)行的抽樣。
hive (default)> select * from stu tablesample(0.1 percent) ;
尖叫提示:這種抽樣方式不一定適用于所有的文件格式。另外,這種抽樣的最小抽樣單元是一個(gè)HDFS數(shù)據(jù)塊。因此,如果表的數(shù)據(jù)大小小于普通的塊大小128M的話,那么將會(huì)返回所有行。