这可以从字符串手动构建Spark DataType吗?

时间:2017-03-21 11:31:35

标签: scala apache-spark

我需要从字符串手动构建Spark DataTypes取决于列的DataType。 我尝试过不同的方式,如:

dataType match {
  case IntegerType => DataTypes.IntegerType(data.toInt)

但是找不到正确的方法。这可能吗? 我需要将给定的字符串值与列中的值进行比较。

1 个答案:

答案 0 :(得分:0)

据我所知,您已经拥有了数据结构,但希望根据Spark的DataTypes转换数据类型。我假设,没有嵌套序列或数组。

object DataTypeUtil {

  def anyValueOfStringWithDataType(dataWithType: (String, DataType)): Any = {
    val dataType = dataWithType._2
    val data = dataWithType._1
    dataType match {
      case _: StringType => data
      case _: IntegerType => Integer.valueOf(data)
      case _ => throw new IllegalArgumentException
    }
  }

  def stringsToRows(values: Seq[String], dataTypes: Seq[DataType]): Row =
    Row.fromSeq(values.zip(dataTypes).map(anyValueOfStringWithDataType))

}
相关问题