使用Scala在Spark中根据列值限制的广播Map上执行查找

时间:2019-06-11 16:00:48

标签: scala apache-spark apache-spark-sql

我想在myMap上进行查找。当col2的值为“ 0000”时,我想用与col1键相关的值来更新它。否则,我想保留现有的col2值。

val myDF :

+-----+-----+
|col1 |col2 |
+-----+-----+
|1    |a    | 
|2    |0000 |
|3    |c    |
|4    |0000 |
+-----+-----+

val myMap : Map[String, String] ("2" -> "b", "4" -> "d")
val broadcastMyMap = spark.sparkContext.broadcast(myMap)

def lookup = udf((key:String) => broadcastMyMap.value.get(key))

myDF.withColumn("col2", when ($"col2" === "0000", lookup($"col1")).otherwise($"col2"))

我在spark-shell中使用了上面的代码,它可以正常工作,但是当我构建应用程序jar并使用spark-submit将其提交给Spark时,会抛出错误:

org.apache.spark.SparkException: Failed to execute user defined  function(anonfun$5: (string) => string)

Caused by: java.lang.NullPointerException

有没有一种方法可以在不使用UDF的情况下执行查找,这不是性能方面的最佳选择,也不是解决错误的方法? 我想我不能只使用join,因为必须保留一些必须保留的myDF.col2值。

1 个答案:

答案 0 :(得分:1)

您的NullPointerException无效。我使用以下示例程序进行了验证。
其完美的工作效果。您执行以下程序。

package com.example

import org.apache.log4j.{Level, Logger}
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.expressions.UserDefinedFunction


object MapLookupDF {
  Logger.getLogger("org").setLevel(Level.OFF)

  def main(args: Array[String]) {
    import org.apache.spark.sql.functions._

    val spark = SparkSession.builder.
      master("local[*]")
      .appName("MapLookupDF")
      .getOrCreate()
    import spark.implicits._
    val mydf = Seq((1, "a"), (2, "0000"), (3, "c"), (4, "0000")).toDF("col1", "col2")
    mydf.show
    val myMap: Map[String, String] = Map("2" -> "b", "4" -> "d")
    println(myMap.toString)
    val broadcastMyMap = spark.sparkContext.broadcast(myMap)

    def lookup: UserDefinedFunction = udf((key: String) => {
      println("getting the value for the key " + key)
      broadcastMyMap.value.get(key)
    }
    )

    val finaldf = mydf.withColumn("col2", when($"col2" === "0000", lookup($"col1")).otherwise($"col2"))
    finaldf.show
  }
}

结果:

Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
+----+----+
|col1|col2|
+----+----+
|   1|   a|
|   2|0000|
|   3|   c|
|   4|0000|
+----+----+

Map(2 -> b, 4 -> d)
getting the value for the key 2
getting the value for the key 4
+----+----+
|col1|col2|
+----+----+
|   1|   a|
|   2|   b|
|   3|   c|
|   4|   d|
+----+----+

注意:广播的小地图不会有明显的降级。

如果要使用数据框,可以将映射转换为数据框

val df = myMap.toSeq.toDF("key", "val")

Map(2 -> b, 4 -> d) in dataframe format will be like
+----+----+
|key|val  |
+----+----+
|   2|   b|
|   4|   d|
+----+----+

然后像this

一样加入

DIY ...