Hive-Hbase练习之统计用户历史消费金额

需求

假定Hive的person表存储用户当天消费的金额信息,HBase的table2表存储用户历史消费
的金额信息。
现person表有记录name=1,account=100,表示用户1在当天消费金额为100元。
table2表有记录key=1,cf:cid=1000,表示用户1的历史消息记录金额为1000元。
基于某些业务要求,要求开发Spark应用程序实现如下功能:
根据用户名累计用户的历史消费金额,即用户总消费金额=100(用户当天的消费金额)1000(用户历史消费金额)。
要求:
在开始开发应用前,需要创建Hive表,命名为person,并插入数据。同时,创建HBase
table2表,用于将分析后的数据写入。

思路

1 先启动zookeeper集群 hadoop集群 mysql服务 hive服务 spark集群 hbase集群
2 在之前的spark整合hive环境下,进入spark-sql 注意指定hive数据存储的路径

spark-sql
–master spark://node01:7077
–executor-memory 1g
–total-executor-cores 2
–conf spark.sql.warehouse.dir=hdfs://node01:8020/user/hive/warehouse

3 创建hive的person表

create database if not exists homework;
create external table if not exists homework.person(
name string, --用户标识
account bigint --今日消费金额
) partitioned by (dt string)
row format delimited fields terminated by ‘,’
lines terminated by ‘\n’
location ‘/spark_homeword/person’;

alter table homework.person add partition (dt=‘2019-07-14’);

4 将数据加载进person表中

hdfs dfs -put /root/homework_data/person.txt /spark_homeword/person/dt=2019-07-14
person.txt的数据如下:
1,100
2,200
3,400
4,300
5,350

验证是否加载数据成功
在这里插入图片描述

5 在hbase创建table2表 由于做好了hive和hbase的整合 可以在hive创建表直接映射到hbase中 在hive客户端执行

create table hive_table2(
key string, --用户标识
cid bigint–历史总金额
)STORED BY ‘org.apache.hadoop.hive.hbase.HBaseStorageHandler’
WITH SERDEPROPERTIES (“hbase.columns.mapping” = “:key,cf:cid”)
TBLPROPERTIES (“hbase.table.name” = “table2”);

在这里插入图片描述

查看hbase中是否创建
在这里插入图片描述
查看table2的表结构
在这里插入图片描述

7 在hive中创建一张临时表 用于统计用户历史金额和今日金额

create database if not exists adm;
create table if not exists homework.table_tmp(
key string,-- 用户标识
cid bigint–历史消费金额
);

在这里插入图片描述

8 统计用户今日消费金额+历史消费金额 并插入临时表

insert overwrite table homework.table_tmp
select
case when t2.key is NULL then t1.name else t1.name end as key,
case when t2.cid is null then t1.account else t1.account+t2.cid end as cid
from person t1 left join table_tmp t2 on t1.name=t2.key;

第一天的统计结果
在这里插入图片描述
验证第二天的统计结果是否正确 假设第二天当天的用户消费数据还是和第一天的消费数据一样
1,100
2,200
3,400
4,300
5,350

再次统计这两天用户总共的消费数据
insert overwrite table homework.table_tmp
select
case when t2.key is NULL then t1.name else t1.name end as key,
case when t2.cid is null then t1.account else t1.account+t2.cid end as cid
from person t1 left join table_tmp t2 on t1.name=t2.key ;

统计结果如下 说明sql统计正确
在这里插入图片描述

9 将table_tmp表的数据灌入hive_table2 映射到hbase的table2表

insert overwrite table homework.hive_table2 select * from homework.table_tmp;

在这里插入图片描述

10 查看hbase中的数据

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值