前言
本文隶属于专栏《1000个问题搞定大数据技术体系》,该专栏为笔者原创,引用请注明来源,不足和错误之处请在评论区帮忙指出,谢谢!
本专栏目录结构和参考文献请见1000个问题搞定大数据技术体系
正文
静态分区
- 表的分区字段的值需要开发人员手动给定
1、创建分区表
create table order_partition(
order_number string,
order_price double,
order_time string
)
partitioned BY(month string)
row format delimited fields terminated by '\t';
2、准备数据 order_created.txt 内容如下
10001 100 2021-06-02
10002 200 2021-06-02
10003 300 2021-06-02
10004 400 2021-06-03
10005 500 2021-06-03
10006 600 2021-06-03
10007 700 2021-06-04
10008 800 2021-06-04
10009 900 2021-06-04
3、加载数据到分区表
load data local inpath '/opt/bigdata/data/order_created.txt' overwrite into table order_partition partition(month='2021-06');
4、查询结果数据
select * from order_partition where month='2021-06';
结果为:
10001 100.0 2021-06-02 2021-06
10002 200.0 2021-06-02 2021-06
10003 300.0 2021-06-02 2021-06
10004 400.0 2021-06-03 2021-06
10005 500.0 2021-06-03 2021-06
10006 600.0 2021-06-03 2021-06
10007 700.0 2021-06-04 2021-06
10008 800.0 2021-06-04 2021-06
10009 900.0 2021-06-04 2021-06
动态分区
- 按照需求实现把数据自动导入到表的不同分区中,不需要手动指定
需求:按照不同部门作为分区导数据到目标表
1、创建表
--创建普通表
create table t_order(
order_number string,
order_price double,
order_time string
)row format delimited fields terminated by '\t';
--创建目标分区表
create table order_dynamic_partition(
order_number string,
order_price double
)partitioned BY(order_time string)
row format delimited fields terminated by '\t';
2、准备数据 order_created.txt 内容如下
10001 100 2021-06-02
10002 200 2021-06-02
10003 300 2021-06-02
10004 400 2021-06-03
10005 500 2021-06-03
10006 600 2021-06-03
10007 700 2021-06-04
10008 800 2021-06-04
10009 900 2021-06-04
3、向普通表 t_order 加载数据
load data local inpath '/opt/bigdata/data/order_created.txt' overwrite into table t_order;
4、动态加载数据到分区表中
---要想进行动态分区,需要设置参数
hive> set hive.exec.dynamic.partition=true; //使用动态分区
hive> set hive.exec.dynamic.partition.mode=nonstrict; //非严格模式
insert into table order_dynamic_partition partition(order_time) select order_number,order_price,order_time from t_order;
--注意字段查询的顺序,分区字段放在最后面。否则数据会有问题。
5、查看分区
hive> show partitions order_dynamic_partition;
OK
order_time=2021-06-02
order_time=2021-06-03
order_time=2021-06-04
Time taken: 0.01 seconds, Fetched: 3 row(s)
版权声明:本文为Shockang原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。