首先,我们看一下动态分区和静态分区的区别和使用场景

  • 静态分区:

定义:对于静态分区,从字面就可以理解:表的分区数量和分区值是固定的。静态分区需要手动指定,列是在编译时期通过用户传递来决定的。

应用场景:需要提前知道所有分区。适用于分区定义得早且数量少的用例,不适用于生产。

  • 动态分区:

定义:是基于查询参数的位置去推断分区的名称,只有在 SQL 执行时才能确定,会根据数据自动的创建新的分区。

应用场景:有很多分区,无法提前预估新分区,动态分区是合适的,一般用于生产环境。


Hive动态分区插入方式有很多种,我们看官方文档的一段描述:点击直达链接

In the dynamic partition inserts, users can give partial partition specifications, which means just specifying the list of partition column names in the PARTITION clause. The column values are optional. If a partition column value is given, we call this a static partition, otherwise it is a dynamic partition. Each dynamic partition column has a corresponding input column from the select statement. This means that the dynamic partition creation is determined by the value of the input column. The dynamic partition columns must be specified last among the columns in the SELECT statement and in the same order in which they appear in the PARTITION() clause. As of Hive 3.0.0 (HIVE-19083) there is no need to specify dynamic partition columns. Hive will automatically generate partition specification if it is not specified.

红色字体大概意思是:当采用select 方式插入动态分区表时,动态分区的列一定要放在select查找字段的最后一个,从Hive3.0开始,不需要指定动态分区列,Hive会自动识别动态分区列(此时用select时,动态分区的列也要放在最后一个)

创建动态分区表:

create table dept_partition_dy(id int, name string) 
partitioned by (loc int) row format delimited fields terminated by '\t';

几种插入方式:

1、不指定动态分区列,Hive3.0自动识别(Hive2.0应该会报错),这种方式不需要设置非严格模式。

下面sql语句Hive3.0会自动根据select的最后一个查找字段动态分区。

insert into table dept_partition_dy select deptno, dname,loc from dept;

2、放入静态分区

insert into table dept_partition_dy partition(loc='888') select deptno, dname from dept;

结果如下:

3、放入动态分区,必须在非严格模式下执行(效果同1)

set hive.exec.dynamic.partition.mode = nonstrict;
insert into table dept_partition_dy partition(loc) select deptno, dname, loc from dept;

4、不指定分区列的情况下(注意此时要走mr任务,加载的数据在所有mapredue集群上都要有),通过load加载到动态分区,这里一定要注意如下:

(1)如果加载的数据的列数 等于 分区表的非分区列数+分区列数,则效果同方式1(这也是Hive3.0的特性),比如dept.txt输入为

10	ACCOUNTING	1700
20	RESEARCH	1800
30	SALES	1900
40	OPERATIONS	1700

执行下列sql

load data local inpath 'data/dept.txt' into table dept_partition_dy;

会按照第三列自动进行分区。

(2)如果加载的数据的列数 不等于 分区表的非分区列数+分区列数,而加载的数据的列数 等于 分区表的非分区列数,比如dept_min.txt为

10	ACCOUNTING
20	RESEARCH
30	SALES
40	OPERATIONS

执行下列sql

load data local inpath 'data/dept_min.txt' into table dept_partition_dy;

则会将数据加载到默认分区,如下所示:

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐