2017-07-17 79 views
1

簡單的問題,我有一個數組是這樣的:如何名稱和類型的數組正確映射到StrucField

val t = StructField("attName", DecimalType,true) 

type mismatch, expected: DataType, actual: DecimalType.type 

我想創建一個案例類至極可能是有用的全自動生成的數組structField。所以我開始嘗試這個。

case class MyClass1(attributeName: String, attributeType: DataType) 

爲了創建我的測試1:

val test1 = Array(
    MyClass1("att1", StringType), 
    MyClass1("att2", IntegerType), 
    MyClass1("att3", DecimalType) 
) 

因爲DecimalType第三行引發的錯誤這是錯誤的。 (DecimalType不是數據類型)。所以我嘗試了第二個這樣的案例。

case class MyClass2[T](attributeName: String, attributeType: T) 

val test2 = Array(
    MyClass2("att1", StringType), 
    MyClass2("att2", IntegerType), 
    MyClass2("att3", DecimalType) 
) 

現在可以,但下面的行不起作用,因爲Decimal不是DataType。

val myStruct = test2.map(x => 
    StructField(x.attributeName,x.attributeType, true) 
) 

所以這裏是我的問題。如何用DecimalType創建一個StructField,你認爲我的caseclass是一個好方法嗎?由於

回答

2

DecimalType不是單 - 它必須與給定精度和規模進行初始化:

import org.apache.spark.sql.types.{DataType, DecimalType} 

DecimalType(38, 10): DataType 
org.apache.spark.sql.types.DataType = DecimalType(38,10) 

話雖這麼說StructField已經是一個案例類,並提供缺省參數nullabletrue )和metadata所以另一種表示看起來是多餘的。

相關問題