2017-09-05 42 views
0

我正尝试创建一个具有动态模式生成的数据框。下面的代码片段:无法为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

+0

如果类“公制”是内部的,则可能会出现此类错误。将类“公制”移至自己的文件。 – pasha701

+0

我曾尝试将案例类移至单独的文件,但错误仍然存​​在。 –

回答

0

我的电脑上运行良好星火1.6,我打印“convertMetricList”函数的结果。 也许问题在“metricField”字段“计数”类型。在提及你的踪迹 “BIGINT”,在我的ENV类型为 “LongType”:

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

您可以检查你的ENV “metricField” 类型。如果不同,解决方法是硬编码度量结构。

+0

感谢您的回答,我已经在Spark 1.6上测试了我的代码并且它可以工作。我不知道在2.0中发生了什么变化,导致它停止工作。 –

+0

显然这是在1.6中意外实现的,并从2.0中删除。 https://issues.apache.org/jira/browse/SPARK-15507 –

+0

我也面临同样的问题。任何解决方案或解决这些问题 –