3. 数据处理和表优化

3. 数据处理和表优化

3.1 数据导入

beeline -n hive -p进入hql命令行

创建一个临时表,并加载csv数据文件加载到其中。

CREATE TEMPORARY TABLE temp_user_behavior (
`user_id` string comment 'user ID',
`item_id` string comment 'item ID',
`category_id` string comment 'category ID',
`behavior_type` string  comment 'behavior type among pv, buy, cart, fav',
`timestamp` int comment 'timestamp')
row format delimited
fields terminated by ','
lines terminated by '\n'
STORED AS TEXTFILE;

LOAD DATA LOCAL INPATH '/root/Hive/UserBehavior.csv' OVERWRITE INTO TABLE temp_user_behavior ;

创建用户行为表1。

drop table if exists user_behavior1;
create table user_behavior1 (
`user_id` string comment 'user ID',
`item_id` string comment 'item ID',
`category_id` string comment 'category ID',
`timestamp` timestamp comment 'timestamp'
)
PARTITIONED BY (`date` date, `behavior_type` string comment 'behavior type among pv, buy, cart, fav')
row format delimited
fields terminated by ','
lines terminated by '\n'
STORED AS ORC
TBLPROPERTIES ("orc.compress"="SNAPPY");

这里使用以列优先的存储格式,定义压缩算法为snappy,对于像电商分析这样主要查询列的项目,会提高很多效率。同时对日期date进行分区,以及用户行为behavior_type进行分区是一种合理的分区方法,在后续分析过程中将大大提高查询速度。

将数据导入到ORC表中,hive会自动执行 行列转化

查看一共多少条数据。

3.2 数据清洗

DISTRIBUTE BY date, behavior_type这个是用来指定数据分发的策略,它会根据分区键的值将数据分发到不同的reduce任务中,每个reduce任务只处理一个分区的数据。这样就可以在每个分区内部去重,而不需要到全局数据去比较,所以效率高很多。在hdfs上,表按照 date, behavior_type分区后,分区的文件夹数量= date分区数* behavior_type分区数。当DISTRIBUTE BY date, behavior_type;时,可以理解为是在date分区数* behavior_type分区数 这么多个局部中比较去重。

同时如果DISTRIBUTE BY date, behavior_type粒度划分的太细,导致启动的容器太多,计算时间占比较低,可以选择只DISTRIBUTE BY一个。

Last updated