use*_*499 2 scala apache-spark
我有一个示例数据框,如下所示:
val df = Seq((Seq("abc", "cde"), 19, "red, abc"), (Seq("eefg", "efa", "efb"), 192, "efg, efz efz")).toDF("names", "age", "color")
Run Code Online (Sandbox Code Playgroud)
以及如下用户定义的函数,它用字符串长度替换 df 中的“颜色”列:
def strLength(inputString: String): Long = inputString.size.toLong
Run Code Online (Sandbox Code Playgroud)
我正在保存 udf 参考以提高性能,如下所示:
val strLengthUdf = udf(strLength _)
Run Code Online (Sandbox Code Playgroud)
当我在执行选择时尝试处理 udf 时,如果我没有任何其他列名,它会起作用:
val x = df.select(strLengthUdf(df("color")))
scala> x.show
+----------+
|UDF(color)|
+----------+
| 8|
| 12|
+----------+
Run Code Online (Sandbox Code Playgroud)
但是,当我想与 udf 处理的列一起选择其他列时,出现以下错误:
scala> val x = df.select("age", strLengthUdf(df("color")))
<console>:27: error: overloaded method value select with alternatives:
[U1, U2](c1: org.apache.spark.sql.TypedColumn[org.apache.spark.sql.Row,U1], c2: org.apache.spark.sql.TypedColumn[org.apache.spark.sql.Row,U2])org.apache.spark.sql.Dataset[(U1, U2)] <and>
(col: String,cols: String*)org.apache.spark.sql.DataFrame <and>
(cols: org.apache.spark.sql.Column*)org.apache.spark.sql.DataFrame
cannot be applied to (String, org.apache.spark.sql.Column)
val x = df.select("age", strLengthUdf(df("color")))
^
Run Code Online (Sandbox Code Playgroud)
我在这里错过了val x = df.select("age", strLengthUdf(df("color")))
什么?
不能在 select 语句中混合使用字符串和列。
这将起作用:
df.select(df("age"), strLengthUdf(df("color")))
Run Code Online (Sandbox Code Playgroud)