hive 外部分区表的创建与应用

本文介绍了在Hive中创建和使用外部分区表的步骤,以保护源日志数据。通过创建外部表并按日期进行分区,便于管理和查询大量日志数据。详细步骤包括:1) 创建外部表的初始化文件和执行建表语句;2) 动态添加分区并与源日志文件关联;3) 查询特定日期分区的数据。此外,还展示了如何通过shell脚本和cron任务实现自动分区添加。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

工作中经常会用到hive的外部分区表,对清理后的日志建hive的外部表,为什么要对它创建外部表呢?因为当删除hive表时,删除的只是表的定义等,但是删除不了源日志内容,对源日志的保护非常重要。分区一般按日期来分区的。
步骤:
1.创建外部表:
 1.1、创建初始化文件(方便后期重复使用):vi init.hql  
 1.2、在init.hql中写建表语句:
    CREATE external TABLE msg_external (
        ip string,
        ctime string,
        status string,
        account string,
        an string,
        c string,
        cid string,
        lan string,
        m string)
    partitioned by (dt string) 
    row format delimited 
    fields terminated by '\t'
    ;
1.3、执行init.hql,完成此外部分区表的表结构创建。
hive -f init.hql
2.创建真正的分区,将分区关联源日志文件
alter table msg_external  add partition(dt='201601') location '/user/hdfs/clean_log/msg/201601/';
alter table msg_external  add partition(dt='201602') location '/user/hdfs/clean_log/msg/201602/';
alter table msg_external  add partition(dt='201603') location '/user/hdfs/clean_log/msg/201603/';
.
.
.
alter table msg_external  add partition(dt='201812') location '/user/hdfs/clean_log/msg/201812/';
此时201601的数据已经加载好了。
3.查询数据 
    select * from msg_external  where dt='201601'  limit   10; 
   此时能查询出数据。当日期到了20160201日时,就能查询出dt='201602'的数据。

对于第2步,其实可以做成动态的。
1.创建add_partition_init.hql
    在add_partition_init.hql中写上语句:
alter table msg_external  add partition(dt ='${hivevar:month}') location '/user/hdfs/clean_log/msg/'${hivevar:month}'/';
2.创建add_partition_init.sh
    #!/usr/bin/env bash
        month=`date "+%Y%m" `
        
        hive -hivevar month="${month}"  -f '/home/root/msg/add_partition_init.hql';

3.加入定时 crontab -e
0 0 1 * * cd /home/root/msg; nohup sh add_partition_init.sh > /home/root/runtime_log/add_partition_init.log 2>&1  &
(每月的1号0点0分的时候开始调用创建分区的shell语句)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值