利用反射机制推断RDD模式

现有数据如格式, Andy,30
将其加载为DataFrame文件。

  1. import spark.implicits._
  2. case class Person(name: String, age: Long)
  3. spark.textFile('people.txt').map(_.split(",")).map(attributes=> Person(attributes(0),attributes(1).trim.toInt)).toDF()

使用编程方式定义RDD模式

当无法提前定义case class时,就需要采用编程方式定义RDD模式。
1)制作表头
2)制作表中的记录
3)把表头和记录拼接在一起

表头即表的schema,包括了字段名称、类型和是否有空值情况

val fields = Array(StructField("name",StringType,true),StructField("age",IntegerType,true))
val schema =  StructType(fields)
val rowRDD = spark.textFile('people.txt').map(_.split(",")).map(attributes=> Person(attributes(0),attributes(1).trim.toInt))
val df = spark.createDataFrame(rowRDD, schema)