大数据开发Hive综合案例(第十九篇)

92 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第6天,点击查看活动详情

一、综合案例

1.1、需求描述

Flume按天把数据采集到HDFS中对应的目录中,使用SQL按天统计每天数据的相关指标分析一下:

1.2、Flume思路

Flume按天把日志数据保存到HDFS的对应目录中,针对Flume的source可以使用execsource,channel可以使用基于文件的或者内存的,sink使用hdfssink,在hdfssink的path路径中需要使用%Y%m%d获取日期,将每天的日志数据采集到指定的hdfs目录中

1.3、Hive思路

对按天采集的日志数据建表,由于这份数据可能会被多种计算引擎使用,所以建议使用外部表,这样就算我们不小心把表删除了,数据也还是在的,不影响别人的使用。还有这份数据是按天分目录存储的。在实际工作中,离线计算的需求大部分都是按天计算的,所以在这里最好在表中增加日期这个分区字段,所以最终决定使用外部分区表

二、测试数据查看

image-20221016164921735

通常解决方案:

先写一个mapreduce数据清洗任务,只需要map阶段就行了,对json格式的数据进行解析,把里面每个字段的值全部解析出来,拼成一行,字段值中间可以使用逗号分隔,然后再基于解析之后的数据在hive中建表就可以了。

但是这样的解决方案比较麻烦,还需要些mapreduce

优化思路:

  1. 先基于原始的json数据创建一个外部分区表,表中只有一个字段,保存原始的json字符串即可,分区字段是日期和数据类型
  2. 再创建一个视图,视图中实现的功能就是查询前面创建的外部分区表,在查询的时候会解析json数据中的字段
  3. 这样以后我们就可以直接查询视图就可以查询出我们需要的字段信息了。并且不需要写代码
2.1、创建表
create external table ex_par_more_type(
log string
)partitioned by(create_date string,data_type string) 
 row format delimited 
 fields terminated by '\t'
 location '/moreType';

image-20221016165747737

2.2、加载数据

此时的数据已经在hdfs了,所以不需要load命令了。只需要一个alter命令添加分区信息就可以了。

alter table ex_par_more_type add partition(create_date='20221001',data_type='userInfo') location '/moreType/20221001/userInfo';

alter table ex_par_more_type add partition(create_date='20221001',data_type='giftInfo') location '/moreType/20221001/gift_info';

alter table ex_par_more_type add partition(create_date='20221001',data_type='videoInfo') location '/moreType/20221001/videoInfo';

image-20221016170637730

查询数据

image-20221016170824003

2.3、创建视图
create view gift_record_view as select get_json_object(log,'$.id') as id,
get_json_object(log,'$.start_time') as start_time,
get_json_object(log,'$.type') as type,
create_date
from ex_par_more_type
where data_type='giftInfo';

image-20221016171202662

image-20221016171252278

2.4、编写脚本

上面其实还没完,因为后期flume每天都会采集新的数据上传到hdfs上面,所以我们需要每天都做一次添加分区的操作。所以需要开发脚本:脚本名称:addPartition.sh

#!/bin/bash
# 每天凌晨1点定时添加当天日期的分区
if [ "a$1" = "a" ]
then
current_date=`date +%Y%m%d`
else
current_date=$1
fi
# 指定添加分区操作
hive -e "
alter table ex_par_more_type add if not exists partition(create_date='${current_date}',data_type='userInfo') location '/moreType/${current_date}/userInfo';
alter table ex_par_more_type add if not exists partition(create_date='${current_date}',data_type='giftInfo') location '/moreType/${current_date}/gift_info';
alter table ex_par_more_type add if not exists partition(create_date='${current_date}',data_type='videoInfo') location '/moreType/${current_date}/videoInfo';
"
  1. 执行脚本

    sh addPartition.sh

  2. 这个脚本需要配置一个定时任务,每天凌晨1点执行,可以使用crontab

    00 01 * * * root /bin/bash /root/sh/addPartition.sh >> /root/sh/addPartition.log