抽样语法
(https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Sampling)
1. 分桶表 抽样
table_sample: TABLESAMPLE (BUCKET x OUT OF y [ON colname])
说明
- 分桶语句中分母表示的将会被散列的桶的个数,分子表示会选择的桶的个数。
- tablesample子句允许用户通过hive query查询抽样数据来替代整个表的数据。
- tablesample子句可以添加至from任何表的子句中。
- 分桶的序号从1开始标记。
- 其中colname的含义是表中每一行的数据都是通过这列来抽样。
- colname可以是表中非分区字段
- colname=rand()含义是替代特定的列来抽样所有的数据行。
- 表中所有数据行被随机的分到y个桶中,序号为1至y
- 数据结果返回属于x桶的行数据
例子1.随机返回32个分桶的source表的3个桶数据,其中s为表的重命名,s = “source tablesample(bucket 3 out of 32 on rand())”。
SELECT * FROM source TABLESAMPLE(BUCKET 3 OUT OF 32 ON rand()) s;
分桶表的输入裁剪input pruning:
最为有特色的是,tablesample将直接扫描全表得到抽样数据。但是,这样不是最有效的。替代办法是,建表的时候创建clustered by子句含义是表的列集合是哈希分区/聚集的。如果tablesample子句指定的列匹配clustered by子句的列,那么tablesample仅仅扫描表中符合的哈希分区。
以下理解比较拗口,不太理解,如果有理解的可以发表评论告知,谢谢!
Example:
So in the above example, if table 'source' was created with 'CLUSTERED BY id INTO 32 BUCKETS'
TABLESAMPLE(BUCKET 3 OUT OF 16 ON id)
would pick out the 3rd and 19th clusters as each bucket would be composed of (32/16)=2 clusters.
On the other hand the tablesample clause
TABLESAMPLE(BUCKET 3 OUT OF 64 ON id)
would pick out half of the 3rd cluster as each bucket would be composed of (32/64)=1/2 of a cluster.
tablesample(bucket 3 out of 16 on id)
这个语句将数据分桶的个数为16个,但是表数据有32个桶,所以1个cluster群集包含16个桶,筛选数据表(32个桶)其中序号为3和19的桶数据。
tablesample(bucket 3 out of 64 on id)
这个语句将数据分桶的个数为64个,但是表数据有32个桶,所以只有1/2个cluster群集,筛选序号为3的桶1/2的数据。
For information about creating bucketed tables with the CLUSTERED BY clause, see Create Table (especially Bucketed Sorted Tables) and Bucketed Tables.
2. 数据块 抽样
<1> n%的数据量
获取表数据的n%的数据量,特殊情况,如果当n%的数据小于默认的256M的时候,将返回256M的数据。
block_sample: TABLEAMPLE (n percent)
SELECT * FROM source TABLESAMPLE(0.1 PERCENT) s;
基于百分比的抽样方式提供了一个变量,用于控制基于数据块的调优的种子信息:
set hive.sample.seednumber=<INTEGER>;
<2> 指定数据空间量
user can specify total length to be read, but it has same limitation with PERCENT sampling.
(As of Hive 0.10.0 - https://issues.apache.org/jira/browse/HIVE-3401)
block_sample: TABLESAMPLE (ByteLengthLiteral)
ByteLengthLiteral : (Digit)+ ('b' | 'B' | 'k' | 'K' | 'm' | 'M' | 'g' | 'G')
**例子3**
SELECT *
FROM source TABLESAMPLE(100M) s;
<3> 限制数据行
block_sample: TABLESAMPLE (n ROWS)
For example, the following query will take the first 10 rows from each input split.
SELECT * FROM source TABLESAMPLE(10 ROWS);
最后还可以参考hive官方中文版本电子书第6.9节内容,阐述了样本抽样,附带了例子。