如何在 Scala 中向 sqlContext UDF 注册函数? [英] How do I register a function to sqlContext UDF in scala?
问题描述
我有一个名为 getAge(timestamp:Long) 的方法,我想将其注册为 sql 函数.
I have a method called getAge(timestamp:Long) and I want to register this as a sql function.
我有
sqlContext.udf.register("getAge",getAge)
但它告诉我我需要参数或使用 _ 之后,我尝试使用 _ 但给了我错误.我如何用参数注册它.我是 Scala 的新手,所以我不知道该怎么做.
But its telling me I need arguments or use _ afterwards, I tried using _ but gives me error. How do I register it with an argument. I am new to scala so I have no idea how to do this.
推荐答案
sqlContext.udf.register("getAge",getAge)
应该是:
sqlContext.udf.register("getAge",getAge _)
下划线(函数和下划线之间必须有一个空格)将函数变成可以在注册中传递的部分应用函数.
The underscore (must have a space in between function and underscore) turns the function into a partially applied function that can be passed in the registration.
当我们调用一个函数时,我们必须传入所有需要的参数.如果我们不这样做,编译器会抱怨.
When we invoke a function, we have to pass in all the required parameters. If we don't, the compiler will complain.
然而,我们可以向它请求函数作为值,稍后我们可以使用它传入所需的参数.我们如何做到这一点是使用下划线.
We can however ask it for the function as a value, with which we can pass in the required parameters at a later time. How we do this is to use the underscore.
getAge
表示运行 getAge
- 例如,def getAge = 10
给我们 10
.我们不想要结果,我们想要功能.此外,根据您的定义,编译器发现 getAge
需要一个参数,并抱怨没有给出参数.
getAge
means to run getAge
- for example, def getAge = 10
giving us 10
. We don't want the result, we want the function. Moreover, with your definition, the compiler sees that getAge
requires a parameter, and complains that one wasn't given.
我们在这里要做的是将 getAge
作为函数值传递.我们告诉 Scala,我们还不知道参数,我们希望函数作为一个值,稍后我们将为其提供所需的参数.因此,我们使用 getAge _
.
What we want to do here is to pass getAge
as a function value. We tell Scala, we don't know the parameter yet, we want the function as a value and we'll supply it with the required parameter at a later time. So, we use getAge _
.
假设 getAge
的签名是:
getAge(l: Long): Long = <function>
getAge _
变成匿名函数:
Long => Long = <function>
这意味着它需要一个 Long
类型的参数,调用它的结果将产生一个 Long
类型的值.
which means it needs a parameter of type Long
and the result of invoking it will yield a value of type Long
.
这篇关于如何在 Scala 中向 sqlContext UDF 注册函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!