工作中经常会用到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语句)