【Spark】用udf和withColumn在dafaframe中创建新列

udf使用

import org.apache.spark.sql.functions.udf

udf接收一个函数(func)作为参数,返回一个UserDefinedFunction。

UserDefinedFunction接收列(Column)作为参数,并返回Column.

func可以接收普通类型参数,并返回普通类型结果。

udf会自动把Column入参转化成对应func的入参,并将func返回的结果转化成Column类型。、

注意由于udf限制。func最多接收10个参数

scala 复制代码
import org.apache.spark.sql.functions._
//一个或多个参数
val UDF0= udf{
	(c1:String,c2:Int,...,)=> 函数体
}

df.withColumn("new",UDF0(col("old1"),col("old2")...))

//整行输入
val UDF1= udf{
	(row: Row) => 处理Row类型的函数体,最好返回常规类型
}

val columns = df.columns

df.withColumn("new",UDF1(struct(columns.map(x=>col(x)): _*))

// 注册到sql中使用
 df.createOrReplaceTempView("tempview")
 spark.udf.register("UDF0", UDF0)
 spark.sql("select *, UDF0(struct(`old1`, `old2`, `...`)) as new from tempview").show(100)

struct函数说明:

scala 复制代码
def struct(colName: String, colNames: String*): Column
// Creates a new struct column that composes multiple input columns.
def struct(cols: Column*): Column
// Creates a new struct column. If the input column is a column in a DataFrame, or a derived column expression that is named (i.e. aliased), its name would be retained as the StructField's name, otherwise, the newly generated StructField's name would be auto generated as col with a suffix index + 1, i.e. col1, col2, col3, ...

参考

create-new-column-with-function-in-spark-dataframe

【官方】udf使用
【官方】udf接口
Spark SQL UDF (User Defined Functions)

相关推荐
大大大大晴天2 天前
Hudi Metadata Table 与 Hive Sync (HMS)怎么选?
大数据
手可摘星辰7773 天前
一次线上FlinkCDC异常排查复盘
大数据·flink
大大大大晴天3 天前
Hudi技术内幕:Metadata Table原理与实践
大数据
大大大大晴天4 天前
Hudi技术内幕:深入解析Index索引机制
大数据
阿里云大数据AI技术4 天前
Flink Forward Asia 2026 深圳启幕:Agentic Streaming for AI,开启实时智能新范式
大数据·flink
SelectDB4 天前
阶跃星辰基于 SelectDB 构建 PB 级 Agent 可观测平台
大数据·数据库·aigc
大大大大晴天8 天前
Hudi技术内幕:RecordPayload到RecordMerger
大数据
SelectDB8 天前
秒级弹性、最高降本 70%:SelectDB Serverless 如何重塑云数仓资源效率
大数据·后端·云原生
WhoAmI8 天前
MapReduce框架原理解析一:InputFormat
大数据·hadoop
WhoAmI8 天前
MapReduce框架原理解析三:OutputFormat
大数据·hadoop