给出一个dataframe
作为
+----+
|col1|
+----+
|abc |
|dBf |
|Aec |
+----+
并有udf
功能
import org.apache.spark.sql.functions._
val testUDF = udf{s: String=>s.toUpperCase}
你绝对可以使用另一个类udf
功能
val demo = df.select(testUDF(col("col1")).as("upperCasedCol"))
这应该给你
+-------------+
|upperCasedCol|
+-------------+
|ABC |
|DBF |
|AEC |
+-------------+
但我建议如果可能的话您使用other functions作为UDF功能需要被序列化和反序列化列这将耗费时间和内存比其他可用的功能更多。 UDF功能应该是最后的选择。
您可以使用upper function为你的情况
val demo = df.select(upper(col("col1")).as("upperCasedCol"))
,这将产生相同的输出作为原始udf
功能
我希望答案是有帮助的
更新
因为你的问题是要求提供信息关于如何调用另一个类或对象定义的UDF功能,这里是法
假设你有,你所定义的UDF函数或者说,我建议作为
import org.apache.spark.sql.Column
import org.apache.spark.sql.functions._
object UDFs {
def testUDF = udf{s: String=>s.toUpperCase}
def testUpper(column: Column) = upper(column)
}
您的A类函数的对象是你的问题,我只是增加了一个功能
import org.apache.spark.sql.DataFrame
import org.apache.spark.sql.functions._
class A(df: DataFrame) {
def testMethod(): DataFrame = {
val demo = df.select(UDFs.testUDF(col("col1")))
demo
}
def usingUpper() = {
df.select(UDFs.testUpper(col("col1")))
}
}
然后就可以调用从主要功能如下
import org.apache.spark.sql.SparkSession
object TestUpper {
def main(args: Array[String]): Unit = {
val sparkSession = SparkSession.builder().appName("Simple Application")
.master("local")
.config("", "")
.getOrCreate()
import sparkSession.implicits._
val df = Seq(
("abc"),
("dBf"),
("Aec")
).toDF("col1")
val a = new A(df)
//calling udf function
a.testMethod().show(false)
//calling upper function
a.usingUpper().show(false)
}
}
我想这是多有帮助
是绝对有可能:) –
你问如何从创建UDF方法中的函数?如何为通用函数创建UDF?如何将其传递给testMethod?最终目标是什么? –
你决定接受答案吗? –