spark-DataFrame之RDD和DataFrame之間的轉換(scala)


package cn.spark.study.dataFramecore

import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
import org.apache.spark.sql.SQLContext

object RDD2DataFrameReflection extends App{
val conf = new SparkConf().setAppName("RDD2DataFrameReflection").setMaster("local");
val sc = new SparkContext(conf);
val sqlContext = new SQLContext(sc);
// 在Scala中使用反射方式,進行RDD到DataFrame的轉換,需要手動導入一個隱式轉換
import sqlContext.implicits._
case class Student(id:Int,name:String,age:Int)
// 這里其實就是一個普通的,元素為case class的RDD
// 直接對它使用toDF()方法,即可轉換為DataFrame
//把讀取進來的文字分割然后成為數組一個一個array循環放進student對象中.最后調用toDF生成對象
val studentDF = sc.textFile("D:/students.txt", 1).map{ line => line.split(",")}
.map{arr => Student(arr(0).trim().toInt,arr(1).trim().toString(),arr(2).trim().toInt)}.toDF();
studentDF.registerTempTable("student");
val teenageDF = sqlContext.sql("select * from student where age <= 18");
//DataFrame 轉化為RDD
val teenagerRDD = teenageDF.rdd;
//通過里面的row打印出來
teenagerRDD.map { row => Student(row(0).toString().toInt,row(1).toString(),row(2).toString().toInt) }
.collect().foreach {student => print(student.id + " " + student.name + " " + student.age) }
// 還可以通過row的getValuesMap()方法,獲取指定幾列的值,返回的是個map 進行篩選重組RDD
val studentRDD = teenagerRDD.map { row =>
val map = row.getValuesMap[Any](Array("id","name","age"))
Student(map("id").toString().toInt,map("name").toString(),map("age").toString().toInt)
}
studentRDD.collect().foreach { stu => println(stu.id + ":" + stu.name + ":" + stu.age) }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM