需求二:日活用户相关指标
原创大约 2 分钟
实现思路
实现
日活用户量
的思路:可以直接使用DWS层
的dws_app_open_history
表,直接统计记录数量即可获得日活用户量,并将最终结果保存到APP层
的app_user_active
表中。实现
日活用户量的环/同比
的思路:直接基于app_user_active
表进行计算,然后将结果保存到app_user_active_count
表。
APP层开发
因为这个需求需要的DWS层
表已经有了,所以就可以直接进行APP层
的开发。
首先需要初始化APP层
的app_user_active
和app_user_active_count
表。
> cd /home/work/warehouse_user_action
> vi app_shopmall_requirement02_init.sh
#!/bin/bash
# 需求二:日活用户相关指标
# app层数据库和表初始化,只需要执行一次
hive -e "
create database if not exists app_shopmall;
create external table if not exists app_shopmall.app_user_active (
num int
) partitioned by(dt string)
row format delimited
fields terminated by '\t'
location 'hdfs://server01:9000/data/app/user_active';
create external table if not exists app_shopmall.app_user_active_count (
num int,
day double,
week double
) partitioned by(dt string)
row format delimited
fields terminated by '\t'
location 'hdfs://server01:9000/data/app/user_active_count';
"
接着以相同的方式创建每天自动添加数据分区的脚本。
> cd /home/work/warehouse_user_action
> vi app_shopmall_requirement02_add_partition.sh
#!/bin/bash
# 需求一:日活用户相关指标
# 每天凌晨执行一次
if [ "d$1" = "d" ]
then
dt=`date +%Y%m%d --date="1 days ago"`
else
dt=$1
fi
# 日期格式转换,将 20240101 转换为 2024-01-01
dt_new=`date +%Y-%m-%d --date="${dt}"`
hive -e "
insert overwrite table app_shopmall.app_user_active partition(dt='${dt}') select
count(*) as num
from dws_shopmall.dws_app_open_history
where dt = '${dt}';
insert overwrite table app_shopmall.app_user_active_count partition(dt='${dt}') select
num,
(num - num_yesterday) / num_yesterday as day,
(num - num_last7days) / num_last7days as week
from (
select
dt,
num,
lead(num,1) over(order by dt desc) as num_yesterday,
lead(num,7) over(order by dt desc) as num_last7days
from app_shopmall.app_user_active_count
where dt >= regexp_replace(date_add('${dt_new}', -7), '-', '')
) as t
where dt = '${dt}';
"
可以通过定时任务来执行它。
> crontab -e
# 每天凌晨0点1分执行
1 0 * * * /home/work/warehouse_user_action/app_shopmall_requirement02_add_partition.sh
填充数据
为了验证效果,可以往APP层
的表中填充测试数据。
#!/bin/bash
# 往app层填充数据
for((i=1;i<=31;i++))
do
if [ $i -lt 10 ]
then
dt="2024010"$i
else
dt="202401"$i
fi
echo "app_shopmall_requirement02_add_partition.sh" ${dt}
sh app_shopmall_requirement02_add_partition.sh ${dt}
done
感谢支持
更多内容,请移步《超级个体》。