基于你有一个RDD 和一个Map,你可以直接迭代你的RDD。
假设 Rating 有 3 个字段(rdd1,rdd2,rdd3),我们将它们重命名为 field1、field2 和 field3 以使示例清晰并避免混淆。
给出这个示例输入源:
case class Rating(field1: String, field2: Int, field3: String) // custom case class
val yourRDD = spark.sparkContext.parallelize(
Seq(
Rating("rating1", 1, "str1"), // item 1
Rating("rating2", 2, "str2"), // item 2
Rating("rating3", 3, "str3") // item 3
)
)
yourRDD.toDF.show() // to visualize()
这将输出您的数据源,如下所示:
+-------+------+------+
| field1|field2|field3|
+-------+------+------+
|rating1| 1| str1|
|rating2| 2| str2|
|rating3| 3| str3|
+-------+------+------+
同样,您的地图也有以下示例数据:
val yourMap = Map(
1 -> 1.111,
2 -> 2.222,
3 -> 3.333
)
println(yourMap)
地图上的数据:
yourMap: scala.collection.immutable.Map[Int,Double] = Map(1 -> 1.111, 2 -> 2.222, 3 -> 3.333)
然后,要“合并”,您只需迭代您的RDD,获取您将用作key 的值,在本例中为field2,并将其用作key 的@987654336 @。像这样的:
yourRDD
.map(rating=>{ // iterate each item in your RDD
val key = rating.field2 // get the value from the current item
val valueFromMap = yourMap(key) // look for the value on the map using field2 as key - You need to handle null values in case that you wont have values for all the keys
(key, rating.field3, valueFromMap) // generating an output for a new RDD that will be created based on this
}).toDF.show(truncate=false) // visualize the output
上面的代码会输出:
+---+----+-----+
|_1 |_2 |_3 |
+---+----+-----+
|1 |str1|1.111|
|2 |str2|2.222|
|3 |str3|3.333|
+---+----+-----+
希望对你有帮助