对于Hive分区表,在我们插入数据的时候需要指定对应的分区值,而这里就会涉及很多种情况。比如静态分区插入、动态分区插入、提供的分区值和分区字段类型不一致,或者提供的分区值是NULL的情况,下面我们依次来展现下不同情况下的表现。
1. 静态分区和动态分区
假如建表如下:
create table tbl_name(xxx) partitioned by(pt xxx, online xxx);
Hive默认是静态分区,即明确指定分区值,写法如下:
insert overwrite table tbl_name partition(pt=20121023, if_online=1)
select field1, field2, ..., fieldn
from tbl where xxx;
有时,我们就需要使用动态分区,因为需要根据某些字段来选择插入对应的分区里,不能指定分区值。首先要开启动态分区设置:
set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;
然后写法如下(注意select最后的字段值就是对应这分区值):
insert overwrite table tbl_name partition(pt, if_online)
select field1, field2, ...,