【发布时间】:2017-06-09 07:07:54
【问题描述】:
我正在使用 Spark 1.5.2 使用以下语法从 scala 对象创建数据框。我的目的是为单元测试创建数据。
class Address (first:String = null, second: String = null, zip: String = null){}
class Person (id: String = null, name: String = null, address: Seq[Address] = null){}
def test () = {
val sqlContext = new SQLContext(sc)
import sqlContext.implicits._
val persons = Seq(
new Person(id = "1", name = "Salim",
address = Seq(new Address(first = "1st street"))),
new Person(name = "Sana",
address = Seq(new Address(zip = "60088")))
)
// The code can't infer schema automatically
val claimDF = sqlContext.createDataFrame(sc.parallelize(persons, 2),classOf[Person])
claimDF.printSchema() // This prints "root" not the schema of Person.
}
如果我将 Person 和 Address 转换为 case 类,则 Spark 可以使用上述语法或使用 sc.parallelize(persons, 2).toDF 或使用 sqlContext.createDataFrame(sc.parallelize(persons, 2),StructType) 自动继承架构
我不能使用案例类,因为它不能容纳超过 20 个字段,而且我在类中有很多字段。而且使用 StructType 会带来很多不便。案例类最方便,但不能容纳太多属性。
请帮忙,提前谢谢。
【问题讨论】:
-
我认为,如果您的类扩展 Product trait 并实现其抽象方法,它可能会起作用。 (因为这个签名:
createDataFrame[A <: Product](data: Seq[A]))
标签: apache-spark spark-dataframe