分桶及抽樣查詢
分桶表數(shù)據(jù)存儲類似與MR分區(qū)
分區(qū)針對的是數(shù)據(jù)的存儲路徑芳室;分桶針對的是數(shù)據(jù)文件。
分區(qū)提供一個隔離數(shù)據(jù)和優(yōu)化查詢的便利方式刹勃。不過堪侯,并非所有的數(shù)據(jù)集都可形成合理的分區(qū),
特別是之前所提到過的要確定合適的劃分大小這個疑慮荔仁。
分桶是將數(shù)據(jù)集分解成更容易管理的若干部分的另一個技術(shù)伍宦。
建表:
create table stu_buck(id int, name string)
clustered by(id) into 4 buckets
row format delimited fields terminated by '\t';
desc formatted stu_buck;
]
orient/strip%7CimageView2/2/w/1240)
load導(dǎo)入數(shù)據(jù),發(fā)現(xiàn)未生產(chǎn)四個桶
load data local inpath '/home/data/stu.txt' into table stu_buck;
清空桶表
truncate table stu_buck;
導(dǎo)入數(shù)據(jù)之前乏梁,需要先設(shè)置參數(shù)
set hive.enforce.bucketing=true;
set mapreduce.job.reduces=-1; //自動根據(jù)桶的個數(shù)決定業(yè)務(wù)的個數(shù)
insert into table stu_buck
select id, name from stu;
分桶抽樣查詢
對于非常大的數(shù)據(jù)集次洼,有時用戶需要使用的是一個具有代表性的查詢結(jié)果而不是全部結(jié)果。Hive 可以通過對表進行抽樣來滿足這個需求遇骑。
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 時,抽取(4/2=)2 個bucket 的數(shù)據(jù)媒鼓,當(dāng) y=8 時届吁,抽取(4/8=)1/2 個 bucket 的數(shù)據(jù)。
x 表示從哪個 bucket 開始抽取绿鸣,如果需要取多個分區(qū)瓷产,以后的分區(qū)號為當(dāng)前分區(qū)號加上y。
例如枚驻,table 總 bucket 數(shù)為 4,tablesample(bucket 1 out of 2)株旷,表示總共抽仍俚恰(4/2=)2 個bucket 的數(shù)據(jù)尔邓,抽取第 1(x)個和第 3(x+y)個 bucket 的數(shù)據(jù)
注意:x 的值必須小于等于 y 的值,否會報錯