如何在 Spark Udf 中传递地图?

Wan*_*ing 3 scala user-defined-functions apache-spark

我有个问题。我有一个带有几列的火花数据框,如下所示:

id 颜色
1 红色、蓝色、黑色
2 红色、绿色
3 蓝色、黄色、绿色
...

我还有一个地图文件,看起来像:
Red,0
Blue,1
Green,2
Black,3
Yellow,4

我需要做的是将颜色名称映射到不同的id,例如将“红色,蓝色,黑色”映射到[1,1,0,1,0]的数组中。我这样写代码:

def mapColor(label_string:String):Array[Int]={
var labels = label_string.split(",")
var index_array = new Array[Int](COLOR_LENGTH)
for (label<-labels){
  if(COLOR_MAP.contains(label)){
    index_array(COLOR_MAP(label))=1
  }
  else{
    //dictionary does not contain the label, the last index set to be one
    index_array(COLOR_LENGTH-1)=1
  }
}
index_array 
}
Run Code Online (Sandbox Code Playgroud)

COLOR_LENGTH 是字典的长度,COLOR_MAP 是包含 string->id 关系的字典。

我这样调用这个函数:

 val color_function = udf(mapColor:(String)=>Array[Int])
 sql.withColumn("color_idx",color_function(col("Color")))
Run Code Online (Sandbox Code Playgroud)

由于我有多个列需要这个操作,但是不同的列需要不同的字典。目前,我为每一列复制这个函数(只需更改字典和长度信息)。但是代码看起来很乏味。有没有什么方法,我可以把长度和字典传给映射函数,比如

def map(label_string:String,map:Map[String,Integer],len:Int):Array[Int] 
Run Code Online (Sandbox Code Playgroud)

但是我应该如何在 spark 数据框中调用这个函数呢?由于我无法在声明中传递参数

val color_function = udf(mapColor:(String)=>Array[Int])
Run Code Online (Sandbox Code Playgroud)

Leo*_*o C 8

您可以使用颜色映射附带的 UDF 作为基本参数,如下例所示:

val df = Seq(
  (1, "Red, Blue, Black"),
  (2, "Red, Green"),
  (3, "Blue, Yellow, Green")
).toDF("id", "color")

val colorMap = Map("Red"-> 0, "Blue"->1, "Green"->2, "Black"->3, "Yellow"->4)

def mapColorCode(m: Map[String, Int]) = udf( (s: String) =>
  s.split("""\s*,\s*""").map(c => m.getOrElse(c, -99))
)

df.select($"id", mapColorCode(colorMap)($"color").as("colorcode")).show
// +---+----------+
// | id| colorcode|
// +---+----------+
// |  1| [0, 1, 3]|
// |  2|    [0, 2]|
// |  3| [1, 4, 2]|
// +---+----------+
Run Code Online (Sandbox Code Playgroud)