给定一个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")))
}
}
然后你可以从main调用函数如下
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)
}
}
我想这不仅仅是有用的