1.分区
1.1分区作用
因为hive管理的数据对应存储在hdfs上的文件,所以hive的分区其实本质上就是分文件夹存储。通过指定字段来达到将一个大的结果集在hdfs上分开存储,查询时通过where过滤达到提高查询时间的效果。操作方面分为静态分区和动态分区。
1.2静态分区
create table dept_partition(deptno int, dname string, loc string)partitioned by (month string)row format delimited fields terminated by '\t';load data local inpath '/opt/module/datas/dept.txt' into table default.dept_partition partition(month='201709');---查询select * from dept_partition where month='201709'unionselect * from dept_partition where month='201708'--增加分区alter table dept_partition add partition(month='201705') partition(month='201704');--删除分区alter table dept_partition drop partition (month='201704');--查看所有的分区show partitions dept_partition;
1.3动态分区
动静混合格式:insert into|overwrite table 表名 partition(分区字段1=值1,分区字段2,分区字段3....) +select ....注意: 如果使用动静混合分区, 必须满足以下条件1) 必须配置以下参数:set hive.exec.dynamic.partition=true; 开启动态分区支持set hive.exec.dynamic.partition.mode=nonstrict; 开启非严格模式2) select查询语句结果!!!!!最后面必须是动态分区字段!!!!!,而且要保证顺序
1.4其他注意事项
1.分区排序Distribute by 分区内排序,通常结合sorted by 使用如果 distribute by和sorted by 一起使用的话可以使用cluster by(但是 cluster by 只能降序排序不能自定义升序或者降序)
2.分桶
2.1分桶的作用
并非所有的数据都适合分区。分桶一般通过 hash分桶字段从而达到差分分区内的文件。从而可以在join时减少文件数据集的扫描。另外还可以使用数据抽样的方式查看数据避免扫描大表
create table test_buck(id int, name string)clustered by(id) sorted by (id asc) into 6 bucketsrow format delimited fields terminated by '\t';CLUSTERED BY来指定划分桶所用列;SORTED BY对桶中的一个或多个列进行排序;into 6 buckets指定划分桶的个数。--启用桶表set hive.enforce.bucketing=true;insert into table test_buck select id, name from temp_buck;--桶表的数据必须通过MR插入
2.2抽样
select * from table tablesample(bucket x out of y on column)注意:y必须是table总bucket数的倍数或者因子。例如,table总共分了10份bucket,当y=2时,抽取(10/2=)5个bucket的数据,当y=10时,抽取(10/10=)1个bucket的数据。x表示从哪个bucket开始抽取,如果需要取多个分区,以后的分区号为当前分区号加上y。例如,table总bucket数为6,tablesample(bucket 1 out of 2),表示总共抽取(6/2=)3个bucket的数 据,从第1个bucket开始,抽取第1(x)个和第3(x+y)个和第5(x+y)个bucket的数据。x的值必须小于等于y的值
