说明:在SparkSQL中读外部数据进行读取进行ETL操作时,首先读取的数据格式为RDD数据结构,因此我们一项主要目标就是将读取到的RDD格式转化为DataFrame。
RDD结构转化为DataFrame的形式主要分为两种:①反射②编程Row(StructType)
package LogsAnalyse
import org.apache.spark.sql.{Row, SparkSession}
import org.apache.spark.sql.types.{IntegerType, StringType, StructField, StructType}
/***
* 反射:case class 前提:事先需要知道你的字段、字段类型
* 编程Row 如果第一种情况不能满足你的要求(事先不知道列)
* 选型:优先考虑第一种
*/
object DataFrameRDDApp {
/**
* Row编程创建StructType将RDD转换为DataFrame
* @param args
*/
def main(args: Array[String]): Unit = {
def program(spark:SparkSession): Unit ={
val rdd = spark.sparkContext.textFile("D:\\Data\\students.txt")
println()
val infoRDD=rdd.map(_.split(",")).map(line => Row(line(0).toInt,line(1),line(2).toInt))
val structType = StructType(Array(StructField("id",IntegerType,true),
StructField("name",StringType,true),
StructField("id",IntegerType,true)))
val infoDF = spark.createDataFrame(infoRDD,structType)
infoDF.printSchema()
infoDF.show()
}
/**
* 反射
* @param spark
*/
def Reflection(spark:SparkSession): Unit ={
val spark = SparkSession.builder().appName("DataFrameRDDApp").master("local[2]").getOrCreate()
val rdd = spark.sparkContext.textFile("D:\\Data\\students.txt")
import spark.implicits._
val infoDF = rdd.map(_.split(",")).map(line => Info(line(0).toInt,line(1),line(2).toInt)).toDF()
infoDF.show()
infoDF.filter(infoDF.col("age")>18).show()
//创建零时视图或者表使用SQL方式对DataFrame完成操作
infoDF.createOrReplaceTempView("infos")
spark.sql("select * from infos where age > 18").show()
spark.close()
}
}
case class Info(id:Int,name:String,age:Int)
}