①在HDFS中创建目录/data/userbehavior,并将UserBehavior.csv文件传到该目录。
[root@hadoop02 ~]# hdfs dfs -mkdir -p /data/userbehavior
[root@hadoop02 ~]# hdfs dfs -put /opt/testdata/UserBehavior.csv /data/userbehavior
②通过HDFS命令查询出文档有多少行数据。
[root@hadoop02 ~]# hdfs dfs -cat /data/userbehavior/UserBehavior.csv | wc -l
561294
①在hive中创建数据库exam
②在exam数据库中创建外部表userbehavior,并将HDFS数据映射到表中
create external table if not exists userbehavior(
user_id int ,
item_id int,
category_id int,
behavior_type STRING,
`time` bigint
)
row format delimited fields terminated by ","
stored as textfile location "/data/userbehavior";
③在HBase中创建命名空间exam,并在命名空间exam创建userbehavior表,包含一个列族info
create 'exam:userbehavior','info'
④在hive中创建外部表userbehavior_hbase,并映射到HBase中,并将数据加载到HBase中
create external table userbehavior_hbase(
user_id int,
item_id int,
category_id int,
behavior_type string,
`time` bigint
)
stored by 'org.apache.hadoop.hive.hbase.HBaseStorageHandler'
with serdeproperties ('hbase.columns.mapping'=
":key,info:item_id,info:category_id,info:behavior_type,info:time")
tblproperties ("hbase.table.name"="exam:userbehavior");
⑤请在exam数据库中创建内部分区表userbehavior_partition(按照日期进行分区),并通过查询userehavior表将时间戳格式转化为“年-月-日 时:分:秒”格式,将数据插入至userbehavior_partition表中。
set hive.exec.dynamic.partition = true;
set hive.exec.dynamic.partition.mode = nonstrict;
insert overwrite table userbehavior_partitioned(
select user_id,item_id,category_id,behavior_type,
from_unixtime(`time`) as `time`,
date(from_unixtime(`time`)) dt
from userbehavior);
使用spark,加载hdfs中的UserBehavior.csv文件,并使用RDD完成以下分析。
①统计uv值(一共有多少用户访问淘宝)
scala> fileRDD.map(x=>x.split(",")).filter(x=>x.length==5).map(x=>x(0)).distinct().count
res3: Long = 5458
②分别统计浏览行为点击、收藏、加入购物车、购买的总数量
scala> fileRDD
.map(x=>x.split(","))
.filter(x=>x.length==5)
.map(x=>(x(3),1))
.reduceByKey(_+_)
.foreach(println)
(fav,15017)
(cart,30888)
(buy,11508)
(pv,503881)
①使用spark SQL统计用户最近购买时间。以2017-12-03为当前日期,计算时间范围为一个月,计算用户最近购买时间,时间区间为0-30天,将其分为5档。
0-6、7-12、13-18、25-39分别对应评分4-0
select t1.user_id,
(case when t1.diff between 0 and 6 then 4
when t1.diff between 7 and 12 then 3
when t1.diff between 13 and 18 then 2
when t1.diff between 19 and 24 then 1
when t1.diff between 25 and 30 then 0
else null end) level
from
(select user_id,datediff('2017-12-03',max(dt)) as diff,max(dt) as maxNum
from exam.userbehavior_partitioned where dt>'2017-11-03' and behavior_type='buy'
group by user_id) t1;
②使用spark SQL统计用户消费频率。以2017-12-03为当前日期,计算时间范围为一个月,用户的消费次数从第祷告为1-161次,将其分为5档。
1-32、33-64、65-96、97-128、129-161分别对应评分0-4。
select user_id,
(case
when t.num between 1 and 32 then 0
when t.num between 33 and 64 then 1
when t.num between 65 and 96 then 2
when t.num between 97 and 128 then 3
when t.num between 129 and 161 then 4
else null end) level
from
(select user_id,count(user_id) num from exam.userbehavior_partitioned
where dt between '2017-11-03' and '2017-12-03' and behavior_type='buy'
group by user_id) t;