需求
假定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;