【发布时间】:2018-02-13 16:47:05
【问题描述】:
我正在尝试创建具有动态模式生成的数据框。这是sn-p的代码:
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)
我使用的是 Spark 2.1.0
【问题讨论】:
-
如果类“Metric”是内部的,可能会发生这样的错误。将类“Metric”移动到自己的文件中。
-
我尝试将案例类移动到单独的文件,但错误仍然存在。
标签: scala apache-spark spark-dataframe rdd