首页 > 解决方案 > 如何将 udf 应用于 Dafaframe 上的所有字符串和字符串数组

问题描述

我有这个简单的 UDF 将所有字符串都大写

 val upper = (s: String) => {
        s.toUpperCase

  }

 val upperUDF: UserDefinedFunction = spark.udf.register("upper", upper)

我正在尝试像这样使用UDF,所以我可以获得所有大写所有字符串都是嵌套模式

  def extractNames(schema: StructType): Seq[String] = {
    schema.fields.flatMap { field =>
      field.dataType match {
        case structType: StructType =>
          extractNames(structType).map(field.name + "." + _)
        case _: StringType =>
          field.name :: Nil
        case s: ArrayType if (s.elementType == StringType) =>
          field.name + "." + "element" :: Nil
        case _ =>
          Nil
      }
    }
  }

  extractNames(df.schema)
      .foldLeft(df)({ (memoDF, colName) =>
        memoDF.withColumn(colName, upperUDF(col(colName)))
      })
      .as[B]

但是当我得到一个字符串数组时出现此错误


cannot resolve '`alert`['element']' due to data type mismatch: argument 2 requires integral type, however, ''element'' is of string type.;;

alert 是一个字符串数组

标签: scalaapache-spark

解决方案


推荐阅读