首页 > 解决方案 > 在 Spark SQL Api 中使用 Databricks from_xml_string 函数

问题描述

需要将 Databricks 的from_xml_string函数注册为要在 SQL 中使用的 UDF。

下面的代码介绍了这个想法;

object FromXmlString extends App {

  implicit val spark: SparkSession = SparkSession
    .builder()
    .master("local[*]")
    .getOrCreate()

  // data frame contains field col_with_xml that holds XML data
  val df: DataFrame = ???
  df.createOrReplaceTempView("tempView")
  // schema to be applied for col_with_xml field
  val xmlSchema: StructType = ???

  import com.databricks.spark.xml.from_xml_string
  import org.apache.spark.sql.functions.udf
  // with the idea of https://stackoverflow.com/a/49714640
  val testUdf = udf((xml: String) => {

    from_xml_string(xml, xmlSchema)
  }, xmlSchema)

  spark.udf.register("from_xml_string", testUdf)
  // using Spark SQL Api is required
  val sql = "SELECT col1, from_xml_string(col_with_xml) as from_xml FROM tempView"

  spark.sql(sql).show(false) // org.apache.spark.SparkException: Task not serializable
}

此代码导致异常 - 任务不可序列化。

有人可以帮忙吗?提前谢谢了。

标签: sqlxmlapache-sparkuser-defined-functionsdatabricks

解决方案


推荐阅读