[英]Encoders.product[of a scala trait ].schema in spark
如何從特征創建火花模式? 考慮一個特征:
trait A{
val name:String
val size:String
}
作為:
Encoders.product[A].schema
給出:
Error:type arguments do not conform to method product's type parameter bounds [T <: Product]
此外,字段數將超過 case class parameters > 200 的限制
案例 class 確實支持超過 22 列,請嘗試在所有其他類/對象之外創建。 如果您需要創建一個包含大量字段的 dataframe 架構,這應該可行。
val schema: StructType = StructType(
Array(
StructField(name = "name", StringType),
StructField(name = "size", StringType)
)
)
val data = Seq(Row("Ramanan","29"))
spark.createDataFrame(spark.sparkContext.parallelize(data),schema).show()
我不能告訴你為什么這不起作用的所有細節,但我提出了一個我們在 Scala Spark 項目中經常使用的稍微替代的解決方案。
Encoders.product
的簽名看起來像
product[T <: scala.Product](implicit evidence$5 : scala.reflect.runtime.universe.TypeTag[T])
這意味着 tt 期望 class 擴展Product
特征和隱式 TypeTag。
您可以創建case class
而不是特征,因為案例類會自動擴展Product
(和Serializable
)。
為了獲得一個模式,你可以這樣做:
case class A (
val name: String,
val size: String
)
def createSchema[T <: Product]()(implicit tag: scala.reflect.runtime.universe.TypeTag[T]) = Encoders.product[T].schema
val schema = createSchema[A]()
schema.printTreeString()
/*
root
|-- name: string (nullable = true)
|-- size: string (nullable = true)
*/
正如一開始所說,我無法解釋所有細節,只是提供一個可行的解決方案並希望它能滿足您的需求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.