2017-03-21 48 views
-1

我需要從字符串手動構建Spark DataTypes取決於列的DataType。 我試着以不同的方式,如:這是可能的從字符串手動構建Spark DataType?

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

,但無法找到正確做到這一點。這可能嗎? 我需要將字符串中給定的值與列中的值進行比較。

回答

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)) 

} 
+0

但不會這Integer.valueOf(數據)返回值就像Scala Integer而不是IntegerType? – user2975535

+1

是的,它只是返回任何Scala類型。從Scala類型到Spark類型的實際轉換在Row.fromSeq中完成。 –