【问题标题】:Unable to create DataFrame for RDD无法为 RDD 创建 DataFrame
【发布时间】: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


【解决方案1】:

在我的计算机上使用 Spark 1.6 运行良好,我打印了“convertMetricList”函数的结果。 可能在“metricField”字段“count”类型中出现问题。在您提到的跟踪“bigint”中,我的环境类型是“LongType”:

StructField(total,ArrayType(
    StructType(StructField(name,StringType,true), 
    StructField(count,LongType,false)
),true),true)

您可以在您的环境中检查“metricField”类型。如果不同,解决方法是硬编码 Metric 结构。

【讨论】:

  • 感谢您的回答,我已经在 Spark 1.6 上测试了我的代码,并且可以正常工作。我不知道 2.0 中的哪些变化使它停止工作。
  • 显然这是在 1.6 中意外实现的,并从 2.0 中删除。 issues.apache.org/jira/browse/SPARK-15507
  • 我也面临同样的问题。解决这些问题的任何解决方案或解决方法
猜你喜欢
  • 1970-01-01
  • 2017-05-29
  • 1970-01-01
  • 2019-10-20
  • 1970-01-01
  • 2018-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多