scala 如何注册UDF以在SQL和DataFrame中使用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/43484269/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to register UDF to use in SQL and DataFrame?
提问by ninja
From what I have seen, in order to do this you have to
从我所看到的,为了做到这一点,你必须
- make the 
udfas a plain function register the function with
SQLContextfor SQLspark.sqlContext.udf.register("myUDF", myFunc)turn this into a
UserDefinedFunctionforDataFramedef myUDF = udf(myFunc)
- 使之
udf成为一个普通的函数 使用
SQLContextfor SQL注册函数spark.sqlContext.udf.register("myUDF", myFunc)把它变成一个
UserDefinedFunctionforDataFramedef myUDF = udf(myFunc)
Is there no way to combine this into one step and make the udfavailable for both? Also, for cases where a function exists for DataFramebut not for SQL, how do you go about registering it without copying over the code again?
有没有办法将其合并为一个步骤并使udf两者都可用?此外,对于函数存在DataFrame但不用于 SQL 的情况,您如何在不再次复制代码的情况下注册它?
回答by zero323
UDFRegistration.registervariants, which take a scala.FunctionN, return an UserDefinedFunctionso you can register SQL function and create DSL friendly UDF in a single step:
UDFRegistration.register变体,它采用scala.FunctionN,返回 ,UserDefinedFunction因此您可以在一个步骤中注册 SQL 函数并创建 DSL 友好的 UDF:
val timesTwoUDF = spark.udf.register("timesTwo", (x: Int) => x * 2)
spark.sql("SELECT timesTwo(1)").show
+---------------+
|UDF:timesTwo(1)|
+---------------+
|              2|
+---------------+
spark.range(1, 2).toDF("x").select(timesTwoUDF($"x")).show
+------+
|UDF(x)|
+------+
|     2|
+------+
回答by dansuzuki
You can use the following and still apply it on dataframe
您可以使用以下内容并仍然将其应用于数据帧
spark.sqlContext.udf.register("myUDF", myFunc)
Use selectExpr when calling it on dataframe transformations.
在数据帧转换上调用 selectExpr 时使用它。
df.selectExpr("myUDF(col1) as modified_col1")
回答by Shan
Update for Spark2-
Spark2 的更新-
spark.udf.register("func_name", func_name)
spark.udf.register("func_name", func_name)
Argument1- Function name it will be register in spark
Argument1- 将在 spark 中注册的函数名称
Argument2- Function name what is defined while creating in python/scala
Argument2- 在 python/scala 中创建时定义的函数名称
It's best practice to register the function with same name in spark.
最好的做法是在 spark 中注册同名的函数。

