我正嘗試創建一個具有動態模式生成的數據框。下面的代碼片段:無法爲RDD創建數據框
def mapMetricList(row: Row): Seq[Metric] = ???
val fields = Seq("Field1", "Field2")
case class Metric(name: String, count: Long)
def convertMetricList(df: DataFrame): DataFrame = {
val outputFields = df.schema.fieldNames.filter(f => fields.contains(f))
val rdd = df.rdd.map(row => {
val schema = row.schema
val metrics = mapMetricList(row)
val s = outputFields.map(name => row.get(schema.fieldIndex(name)))
Row.fromSeq(s ++ Seq(metrics))
})
val nonMetricsSchema = outputFields.map(f => df.schema.apply(f))
val metricField = StructField("total",ArrayType(ScalaReflection.schemaFor[Metric].dataType.asInstanceOf[StructType]),nullable=true)
val schema = StructType(nonMetricsSchema ++ Seq(metricField))
schema.printTreeString()
val dff = spark.createDataFrame(rdd, schema)
dff
}
但是我一直在運行期間獲得這些例外情況:
Caused by: java.lang.RuntimeException: Metric is not a valid external type for schema of struct<name:string,count:bigint>
at org.apache.spark.sql.catalyst.expressions.GeneratedClass$SpecificUnsafeProjection.evalIfCondExpr3$(Unknown Source)
at org.apache.spark.sql.catalyst.expressions.GeneratedClass$SpecificUnsafeProjection.evalIfFalseExpr4$(Unknown Source)
at org.apache.spark.sql.catalyst.expressions.GeneratedClass$SpecificUnsafeProjection.apply(Unknown Source)
at org.apache.spark.sql.catalyst.encoders.ExpressionEncoder.toRow(ExpressionEncoder.scala:290)
我使用星火2.1.0
如果類「公制」是內部的,則可能會出現此類錯誤。將類「公制」移至自己的文件。 – pasha701
我曾嘗試將案例類移至單獨的文件,但錯誤仍然存在。 –