Spark-shell 据Hive的dwd库中相关表或MySQL数据库shtd_store中订单相关表(order_detail、order_info、sku_info),对用户购买过的商品进行去重,将其转换为以下格式:第一列为用户id mapping(Mapping操作:例如用户id:1、4、7、8、9,则做完mapping操作转为字典类型,键0对应用户id 1,键1对应用户id 4,以此类推),第二列为用户购买过的商品id mapping,按照user_id与sku_id进行升序排序,,最后保存结果到Hive
时间: 2024-02-11 10:05:34 浏览: 112
编译的spark-hive_2.11-2.3.0和 spark-hive-thriftserver_2.11-2.3.0.jar
好的,根据您的需求,我可以提供以下Spark SQL代码实现:
```sql
-- 从Hive中读取订单相关表
CREATE TEMPORARY VIEW dwd_order_detail
AS
SELECT * FROM hive_db.dwd.order_detail;
CREATE TEMPORARY VIEW dwd_order_info
AS
SELECT * FROM hive_db.dwd.order_info;
CREATE TEMPORARY VIEW dwd_sku_info
AS
SELECT * FROM hive_db.dwd.sku_info;
-- 从MySQL中读取shtd_store数据库中的订单相关表
CREATE TEMPORARY VIEW mysql_order_detail
AS
SELECT * FROM jdbc_db.mysql.order_detail;
CREATE TEMPORARY VIEW mysql_order_info
AS
SELECT * FROM jdbc_db.mysql.order_info;
CREATE TEMPORARY VIEW mysql_sku_info
AS
SELECT * FROM jdbc_db.mysql.sku_info;
-- 合并订单相关表
CREATE TEMPORARY VIEW order_detail_union
AS
SELECT * FROM dwd_order_detail
UNION ALL
SELECT * FROM mysql_order_detail;
CREATE TEMPORARY VIEW order_info_union
AS
SELECT * FROM dwd_order_info
UNION ALL
SELECT * FROM mysql_order_info;
CREATE TEMPORARY VIEW sku_info_union
AS
SELECT * FROM dwd_sku_info
UNION ALL
SELECT * FROM mysql_sku_info;
-- 对用户购买过的商品进行去重
CREATE TEMPORARY VIEW user_sku_distinct
AS
SELECT DISTINCT user_id, sku_id
FROM (
SELECT order_detail_union.user_id, order_detail_union.sku_id,
ROW_NUMBER() OVER (PARTITION BY order_detail_union.user_id, order_detail_union.sku_id ORDER BY order_detail_union.order_id) AS rn
FROM order_detail_union
JOIN order_info_union ON order_detail_union.order_id = order_info_union.order_id
WHERE order_info_union.order_status = 'paid'
) t
WHERE rn = 1;
-- 将用户id和sku_id进行mapping操作
CREATE TEMPORARY VIEW user_sku_mapping
AS
SELECT dense_rank() OVER (ORDER BY user_id) - 1 AS user_id_mapping,
dense_rank() OVER (ORDER BY sku_id) - 1 AS sku_id_mapping
FROM user_sku_distinct;
-- 按照user_id_mapping和sku_id_mapping进行升序排序
CREATE TEMPORARY VIEW user_sku_sorted
AS
SELECT user_id_mapping, sku_id_mapping
FROM user_sku_mapping
ORDER BY user_id_mapping, sku_id_mapping;
-- 将结果保存至Hive
INSERT OVERWRITE TABLE hive_db.result.user_sku_mapping
SELECT collect_list(sku_id_mapping) AS sku_id_mapping_list
FROM user_sku_sorted
GROUP BY user_id_mapping;
```
需要注意的是,以上代码中的数据库和表名、字段名等需要根据实际情况进行修改。另外,根据您的要求,最终结果是将用户购买过的商品id mapping按照user_id与sku_id进行升序排序,并将结果保存到Hive中的`hive_db.result.user_sku_mapping`表中,第一列为用户id mapping,这里我将用户id mapping作为结果的索引。
阅读全文