Encoders.product[具有 scala 特征].spark 中的模式
Encoders.product[of a scala trait ].schema in spark
如何根据特征为 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
的限制
我不能告诉你为什么这不起作用的所有细节,但我提出了一个我们经常在我们的 Scala Spark 项目中使用的稍微替代的解决方案。
Encoders.product
的签名看起来像
product[T <: scala.Product](implicit evidence : scala.reflect.runtime.universe.TypeTag[T])
这意味着 tt 期望 class 扩展 Product
特征和隐式 TypeTag。
您可以创建 case class
而不是特征,因为 classes 会自动扩展 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)
*/
如开头所说,我无法解释所有细节,只是提供一个可行的解决方案,希望它能满足您的需求。
案例 class 确实支持超过 22 列,尝试在所有其他 class/object 之外创建。如果您需要创建具有大量字段的数据框模式,这应该可行。
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()
如何根据特征为 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
的限制我不能告诉你为什么这不起作用的所有细节,但我提出了一个我们经常在我们的 Scala Spark 项目中使用的稍微替代的解决方案。
Encoders.product
的签名看起来像
product[T <: scala.Product](implicit evidence : scala.reflect.runtime.universe.TypeTag[T])
这意味着 tt 期望 class 扩展 Product
特征和隐式 TypeTag。
您可以创建 case class
而不是特征,因为 classes 会自动扩展 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)
*/
如开头所说,我无法解释所有细节,只是提供一个可行的解决方案,希望它能满足您的需求。
案例 class 确实支持超过 22 列,尝试在所有其他 class/object 之外创建。如果您需要创建具有大量字段的数据框模式,这应该可行。
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()