HIVE的静态分区和动态分区

静态分区

  • 表的分区字段的值需要开发人员手动指定
    eg: 创建分区表
    create table order_partition(
    order_number string,
    order_price  double,
    order_time string
    )
    partitioned BY(month string)
    row format delimited fields terminated by '\t';
    
    • 准备数据
    cd /bigdata/logs/
    vim order.txt 
    
    10001	100	2019-03-02
    10002	200	2019-03-02
    10003	300	2019-03-02
    10004	400	2019-03-03
    10005	500	2019-03-03
    10006	600	2019-03-03
    10007	700	2019-03-04
    10008	800	2019-03-04
    10009	900	2019-03-04
    
    • 加载数据到分区表
    load data local inpath '/bigdata/logs/order.txt' overwrite into table order_partition partition(month='2019-03');
    
    • 查询结果数据
    select * from order_partition where month='2019-03';
    结果为:
    
    10001	100.0	2019-03-02	2019-03
    10002	200.0	2019-03-02	2019-03
    10003	300.0	2019-03-02	2019-03
    10004	400.0	2019-03-03	2019-03
    10005	500.0	2019-03-03	2019-03
    10006	600.0	2019-03-03	2019-03
    10007	700.0	2019-03-04	2019-03
    10008	800.0	2019-03-04	2019-03
    10009	900.0	2019-03-04	2019-03
    

动态分区

  • 根据分区字段不同的值,自动将数据导入到分区表不同的分区中,不需要手动指定分区字段的值
    eg: 创建表
    -- 创建普通表
    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';
    
    • 准备数据
    cd /bigdata/logs/
    vim order_partition.txt
    
    10001	100	2019-03-02
    10002	200	2019-03-02
    10003	300	2019-03-02
    10004	400	2019-03-03
    10005	500	2019-03-03
    10006	600	2019-03-03
    10007	700	2019-03-04
    10008	800	2019-03-04
    10009	900	2019-03-04
    
    • 向普通表t_order加载数据
    load data local inpath '/bigdata/logs/order_partition.txt' overwrite into table t_order;
    
    • 动态加载数据到分区表中
    -- 要想进行动态分区,需要设置参数
    -- 开启动态分区功能
    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;
    
    • 查看分区
    show partitions order_dynamic_partition;
    

    hive3.x之后, 可以直接通过load的方式导入hdfs上的文件完成动态分区, 并且不需要做任何属性设置, 动态分区会根据最后一个字段来进行分区

    load data inpath '/user/hive/warehouse/myhive.db/t_order' overwrite into table myhive.order_dynamic_partition;
    
posted @ 2021-05-05 17:06  Tenic  阅读(413)  评论(0编辑  收藏  举报