總結下Spark中將RDD轉換成DataFrame的兩種方法, 代碼如下:
- 方法一: 使用
createDataFrame
方法//StructType and convert RDD to DataFrame val schema = StructType( Seq( StructField("name",StringType,true) ,StructField("age",IntegerType,true) ) ) val rowRDD = sparkSession.sparkContext .textFile("/tmp/people.txt",2) .map( x => x.split(",")).map( x => Row(x(0),x(1).trim().toInt)) sparkSession.createDataFrame(rowRDD,schema) } }
- 方法二: 使用
toDF
方法//use case class Person case class Person(name:String,age:Int) //導入隱飾操作,否則RDD無法調用toDF方法 import sparkSession.implicits._ val peopleRDD = sparkSession.sparkContext .textFile("/tmp/people.txt",2) .map( x => x.split(",")).map( x => Person(x(0),x(1).trim().toInt)).toDF()
注意
請不要將case Class
定義在main 方法中與toDF一起使用,或與使用toDF定義在同一函數中