Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
[SPARK-20674][SQL] Support registering UserDefinedFunction as named UDF
  • Loading branch information
rxin committed May 9, 2017
commit 55421ea99a97c6820169a22b1a5bfc00318ac66b
22 changes: 19 additions & 3 deletions sql/core/src/main/scala/org/apache/spark/sql/UDFRegistration.scala
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,31 @@ class UDFRegistration private[sql] (functionRegistry: FunctionRegistry) extends
* @param name the name of the UDAF.
* @param udaf the UDAF needs to be registered.
* @return the registered UDAF.
*
* @since 1.5.0
*/
def register(
name: String,
udaf: UserDefinedAggregateFunction): UserDefinedAggregateFunction = {
def register(name: String, udaf: UserDefinedAggregateFunction): UserDefinedAggregateFunction = {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Is there any change from the previous one at this line?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, I think it's just style change.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it better to change the style?

def builder(children: Seq[Expression]) = ScalaUDAF(children, udaf)
functionRegistry.registerFunction(name, builder)
udaf
}

/**
* Register a user-defined function (UDF), for a UDF that's already defined using the DataFrame
* API (i.e. of type UserDefinedFunction).
*
* @param name the name of the UDF.
* @param udf the UDF needs to be registered.
* @return the registered UDF.
*
* @since 2.2.0
*/
def register(name: String, udf: UserDefinedFunction): UserDefinedFunction = {
def builder(children: Seq[Expression]) = udf.apply(children.map(Column.apply) : _*).expr
functionRegistry.registerFunction(name, builder)
udf
}

// scalastyle:off line.size.limit

/* register 0-22 were generated by this script
Expand Down
7 changes: 7 additions & 0 deletions sql/core/src/test/scala/org/apache/spark/sql/UDFSuite.scala
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,13 @@ class UDFSuite extends QueryTest with SharedSQLContext {
assert(sql("SELECT strLenScala('test')").head().getInt(0) === 4)
}

test("UDF defined using UserDefinedFunction") {
import functions.udf
val foo = udf((x: Int) => x + 1)
spark.udf.register("foo", foo)
assert(sql("select foo(5)").head().getInt(0) == 6)
}

test("ZeroArgument UDF") {
spark.udf.register("random0", () => { Math.random()})
assert(sql("SELECT random0()").head().getDouble(0) >= 0.0)
Expand Down