簡體   English   中英

Spark - 將完整行傳遞給udf,然后在udf中獲取列名

[英]Spark - pass full row to a udf and then get column name inside udf

我正在使用Spark和Scala,並希望將整行傳遞給udf,並選擇side udf中的每個列名和列值。 我怎樣才能做到這一點?

我正在嘗試跟隨 -

inputDataDF.withColumn("errorField", mapCategory(ruleForNullValidation) (col(_*)))

def mapCategory(categories: Map[String, Boolean]) = {
  udf((input:Row) =>  //write a recursive function to check if each row is in categories if yes check for null if null then false, repeat this for all columns and then combine results)   
})

在Spark 1.6中,您可以使用Row作為外部類型,使用struct作為表達式。 作為表達。 可以從架構中獲取列名稱。 例如:

import org.apache.spark.sql.Row
import org.apache.spark.sql.functions.{col, struct}

val df = Seq((1, 2, 3)).toDF("a", "b", "c")
val f = udf((row: Row) => row.schema.fieldNames)
df.select(f(struct(df.columns map col: _*))).show

// +-----------------------------------------------------------------------------+
// |UDF(named_struct(NamePlaceholder, a, NamePlaceholder, b, NamePlaceholder, c))|
// +-----------------------------------------------------------------------------+
// |                                                                    [a, b, c]|
// +-----------------------------------------------------------------------------+

可以使用Row.getAs方法按名稱訪問值。

這是一個簡單的工作示例:

輸入數據:

+-----+---+--------+
| NAME|AGE|CATEGORY|
+-----+---+--------+
|  RIO| 35|     FIN|
|  TOM| 90|     ACC|
|KEVIN| 32|        |
| STEF| 22|     OPS|
+-----+---+--------+

//定義類別列表和UDF

val categoryList = List("FIN","ACC")    
def mapCategoryUDF(ls: List[String]) = udf[Boolean,Row]((x: Row) => if (!ls.contains(x.getAs("CATEGORY"))) false else true)

import org.apache.spark.sql.functions.{struct}
df.withColumn("errorField",mapCategoryUDF(categoryList)(struct("*"))).show()

結果應如下所示:

+-----+---+--------+----------+
| NAME|AGE|CATEGORY|errorField|
+-----+---+--------+----------+
|  RIO| 35|     FIN|      true|
|  TOM| 90|     ACC|      true|
|KEVIN| 32|        |     false|
| STEF| 22|     OPS|     false|
+-----+---+--------+----------+

希望這可以幫助!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM