products一个商品价格变化的表,orders商品订单,记录每次购买商品和日期
基于Spark SQL中的不等值join实现orders和products的匹配,统计每个订单中商品对应当时的价格
缓慢变化的商品价格表
旺仔牛奶,发生过一次价格变更
scala> val products = sc.parallelize(Array(
| ("旺仔牛奶", "2017-01-01", "2018-01-01", 4),
| ("旺仔牛奶", "2018-01-02", "2020-01-01", 5),
| ("王老吉", "2017-01-02", "2019-01-01", 5),
| ("卫龙辣条", "2010-01-01", "2020-01-01", 2)
| )).toDF("name", "startDate", "endDate", "price")
products: org.apache.spark.sql.DataFrame = [name: string, startDate: string ... 2 more fields]
scala> products.show();
+----+----------+----------+-----+
|name| startDate| endDate|price|
+----+----------+----------+-----+
|旺仔牛奶|2017-01-01|2018-01-01| 4|
|旺仔牛奶|2018-01-02|2020-01-01| 5|
| 王老吉|2017-01-02|2019-01-01| 5|
|卫龙辣条|2010-01-01|2020-01-01| 2|
+----+----------+----------+-----+
订单表(商品名称,订单日期)
旺仔牛奶在不同价格时段分别发生了一次订单
scala> val orders = sc.parallelize(Array(
| ("2017-06-01", "旺仔牛奶"),
| ("2017-07-01", "王老吉"),
| ("2018-03-01", "旺仔牛奶")
| )).toDF("date", "product")
orders: org.apache.spark.sql.DataFrame = [date: string, product: string]
scala> orders.show
+----------+-------+
| date|product|
+----------+-------+
|2017-06-01|旺仔牛奶|
|2017-07-01| 王老吉|
|2018-03-01|旺仔牛奶|
+----------+-------+
通过不等值连接,计算每个订单当时的商品价格
查看出旺仔牛奶,两个订单在不同时间段上对应的价格
scala> orders.join(products, $"product" === $"name" && $"date" >= $"startDate" && $"date" <= $"endDate").show()
+-----------+------------+----------+------------+-------------+-----+
| date | product | name | startDate | endDate | price|
+-----------+------------+----------+------------+-------------+-----+
|2017-07-01| 王老吉 | 王老吉 |2017-01-02|2019-01-01 | 5 |
|2017-06-01| 旺仔牛奶 |旺仔牛奶|2017-01-01|2018-01-01 | 4 |
|2018-03-01| 旺仔牛奶 |旺仔牛奶|2018-01-02|2020-01-01 | 5 |
+-----------+------------+----------+------------+-------------+-----+
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。