Spark中使用sql时一些功能需要自定义方法实现,这时候就可以使用UDF功能来实现

多参数支持

UDF不支持参数*的方式输入多个参数,例如String*,不过可以使用array来解决这个问题。

定义udf方法,此处功能是将多个字段合并为一个字段

 

def allInOne(seq: Seq[Any], sep: String): String = seq.mkString(sep)

 

 

在sql中使用

 

sqlContext.udf.register("allInOne", allInOne _)

//col1,col2,col3三个字段合并,使用','分割
val sql =
"""
  |select allInOne(array(col1,col2,col3),",") as col
  |from tableName
""".stripMargin
sqlContext.sql(sql).show()

 

 

在DataFrame中使用

 

import org.apache.spark.sql.functions.{udf,array,lit}
val myFunc = udf(allInOne _)
val cols = array("col1","col2","col3")
val sep = lit(",")
df.select(myFunc(cols,sep).alias("col")).show()

相关文章:

  • 2021-11-12
  • 2021-10-26
  • 2022-12-23
  • 2021-11-19
  • 2021-08-17
  • 2021-09-22
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-02
  • 2021-09-21
  • 2022-12-23
  • 2021-07-06
  • 2021-07-15
相关资源
相似解决方案