【问题标题】:How can I join RDD[Rating] with scala.collection.Map[Int, Double] by key column?如何通过键列加入 RDD[Rating] 和 scala.collection.Map[Int, Double]?
【发布时间】:2020-02-11 13:45:49
【问题描述】:

我有两张桌子 ->

table1: RDD[Rating] (rdd1,rdd2,rdd3)

table2: scala.collection.Map[Int, Double] (m1,m2)

我花了很多时间和精力尝试制作像这样的连接表

(key (key = rdd2 = m1), rdd3, m2)

但我总是有类型不匹配。

您能建议如何处理它吗?我也尝试将两个表都转换为一种类型,但我注意到肯定是不正确的方式......

【问题讨论】:

    标签: scala apache-spark dictionary rdd


    【解决方案1】:

    基于你有一个RDD 和一个Map,你可以直接迭代你的RDD

    假设 Rating 有 3 个字段(rdd1,rdd2,rdd3),我们将它们重命名为 field1field2field3 以使示例清晰并避免混淆。

    给出这个示例输入源:

    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|
    +---+----+-----+
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2019-02-07
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      • 1970-01-01
      • 2016-06-29
      • 2017-04-17
      • 2019-09-22
      • 1970-01-01
      相关资源
      最近更新 更多