简介
分区表实际是对应一个HDFS文件系统上的独立的文件,该文件夹下是该分区所有的数据文件。Hive中的分区就是分目录,把一个大的数据集根据业务需要分割成小的数据集。在查询时通过WHERE子句中的表达式选择查询所需要的指定的分区,这样的查询效率会提高很多。
分区表的基本操作
- 创建分区表
创建语句:
create table dept_partition(id int,name string,loc string) partitioned by (month string) row format delimited fields terminated by '\t' stored as textfile;
!!!!!!!!!!!!!!!!!!!!创建分区的字段不得和表字段重复命名
2. 导入数据
HDFS存储目录:
3. 查询分区表
单分区查询:
select * from dept_partition where month='201701';
多分区查询:
select * from dept_partition where month='201701' union select * from dept_partition where month='201702'
4. 增加分区
语句:alter table dept_partition add partition(month='201704');
5. 增加多个分区
语句:alter table dept_partition add partition(month='201802') partition(month='201803');
6. 删除分区
语句: alter table dept_partition drop partition (month='201701')
删除分区,代表删除这个目录,目录下的数据一并删除。
7. 删除多个分区
语句:alter table dept_partition drop partition(month='201801'),partition(month='201802');
8. 查看分区表有多少分区
语句:show partitions dept_partition;
9. 查看分区表结构
语句:desc formatted dept_partition;
分区表注意事项
- 创建二级分区表
语句:create table dept_partition2(id int,name string) partitioned by (month string,day string) row format delimited fields terminated by '\t' stored as textfile;
- 正常的加载数据
语句:load data local inpath '/home/lzx/data/1.txt' into table dept_partition2 partition(month='201701',day='10');'
- 查询多分区
语句:select * from dept_partition2 where month='201701' and day = '10';
- 把数据直接上传到分区目录上,让分区表和数据产生关联的三种方式
-
方式一:上传数据后修复数据
创建目录:hadoop fs -mkdir -p /user/hive/warehouse/dept_partition2/month=201908/day=12
上传数据:hadoop fs -put text.txt /user/hive/warehouse/dept_partition2/month=201908/day=12
查询数据:select * from dept_partition2 where month='201908' and day = '12';
是查不到数据的
执行修复数据:msck repair table dept_partition2;
查询数据:select * from dept_partition2 where month='201908' and day = '12';
-
方式二:上传数据后添加分区
创建文件:hadoop fs -mkdir -p /user/hive/warehouse/dept_partition2/month=201907/day=11
上传数据:
hadoop fs -put text.txt /user/hive/warehouse/dept_partition2/month=201907/day=11
执行添加分区:alter table dept_partition2 add partition(month='201907',day='11');
查询数据:
-
方式三:创建文件夹后load数据到分区或者直接load
创建目录:hadoop fs -mkdir -p /user/hive/warehouse/dept_partition2/month=201907/day=12
上传数据:
load data local inpath '/home/lzx/tmpfile/text.txt' into table dept_partition2 partition(month='201907',day='12');
查询数据:
当然,你也可以不用创建目录,直接使用load命令导入数据并指明已存在的或者新的分区都可以。
-