Spark SQL and DataFrame
1.為什么要用Spark Sql
原來我們使用Hive,是將Hive Sql 轉換成Map Reduce 然后提交到集群上去執行,大大簡化了編寫MapReduce的程序的復雜性,由於MapReduce這種計算模型執行效率比較慢,所以Spark Sql的應運而生,它是將SparkSql轉換成RDD,然后提交到集群執行,執行效率非常的快。
Spark Sql的有點:1、易整合 2、統一的數據訪問方式 3、兼容Hvie 4、標准的數據連接
2、DataFrames
什么是DataFrames?
與RDD類似,DataFrames也是一個分布式數據容器,然而DataFrame更像是傳統數據庫的二維表格,除了數據以外,還記錄數據的結構信息,即schema。同時,與Hive類似,DataFrame與支持嵌套數據類型(struct、array和map)。從API的易用性上看,DataFrame API提供的是一套高層的關系操作,比函數式的RDD API要更加友好,門檻更低。由於與R和Pandas的DataFrame類似,Spark DataFrame很好地繼承了傳統單機數據分析的開發體驗。

創建DataFrames
在Spark SQL中SQLContext是創建DataFrames和執行SQL的入口,在spark-1。5.2中已經內置了一個sqlContext。
1.在本地創建一個文件,有三列,分別是id、name、age,用空格分隔,然后上傳到hdfs上
hdfs dfs -put person.txt /
2.在spark shell執行下面命令,讀取數據,將每一行的數據使用列分隔符分割
val lineRDD = sc.textFile("hdfs://hadoop01:9000/person.txt").map(_.split(" "))
3.定義case class(相當於表的schema)
case class Person(id:Int, name:String, age:Int)
4.將RDD和case class關聯
val personRDD = lineRDD.map(x => Person(x(0).toInt, x(1), x(2).toInt))
5.將RDD轉換成DataFrame
val personDF = personRDD.toDF
6.對DataFrame進行處理
personDF.show
代碼:
object SparkSqlTest { def main(args: Array[String]): Unit = { val conf = new SparkConf().setMaster("local").setAppName("SQL-1") val sc = new SparkContext(conf) fun1(sc) } //定義case class 相當於表的schema case class Person(id:Int,name:String,age:Int) def fun1(sc:SparkContext): Unit ={ val sqlContext = new SQLContext(sc)
// 位置一般情況下是換成HDFS文件路徑 val lineRdd = sc.textFile("D:\\data\\person.txt").map(_.split(" ")) val personRdd = lineRdd.map(x=>Person(x(0).toInt,x(1),x(2).toInt)) import sqlContext.implicits._ val personDF = personRdd.toDF //注冊表 personDF.registerTempTable("person_df") //傳入sql val df = sqlContext.sql("select * from person_df order by age desc") //將結果以JSON的方式存儲到指定位置 df.write.json("D:\\data\\personOut") sc.stop() }
DataFrame 常用操作
DSL風格語法(個人理解短小精悍的含義)
// 查看DataFrame部分列中的內容 df.select(personDF.col("name")).show() df.select(col = "age").show() df.select("id").show() // 打印DataFrame的Schema信息 df.printSchema() //查詢所有的name 和 age ,並將 age+2 df.select(df("id"),df("name"),df("age")+2).show() //查詢所有年齡大於20的 df.filter(df("age")>20).show() // 按年齡分組並統計相同年齡人數 df.groupBy("age").count().show()
SQL風格語法(前提:需要將DataFrame注冊成表)
//注冊成表 personDF.registerTempTable("person_df") // 查詢年齡最大的兩位 並用對象接接收 val persons = sqlContext.sql("select * from person_df order by age desc limit 2") persons.foreach(x=>print(x(0),x(1),x(2)))
通過StructType直接指定Schema
1 /*通過StructType直接指定Schema*/ 2 def fun2(sc: SparkContext): Unit = { 3 val sqlContext = new SQLContext(sc) 4 val personRDD = sc.textFile("D:\\data\\person.txt").map(_.split(" ")) 5 // 通過StructType直接指定每個字段的Schema 6 val schema = StructType(List(StructField("id", IntegerType, true), StructField("name", StringType, true), StructField("age", IntegerType))) 7 //將rdd映射到RowRDD 8 val rowRdd = personRDD.map(x=>Row(x(0).toInt,x(1).trim,x(2).toInt)) 9 //將schema信息應用到rowRdd上 10 val dataFrame = sqlContext.createDataFrame(rowRdd,schema) 11 //注冊 12 dataFrame.registerTempTable("person_struct") 13 14 sqlContext.sql("select * from person_struct").show() 15 16 sc.stop() 17 18 }
連接數據源
1 /*連接mysql數據源*/ 2 def fun3(sc:SparkContext): Unit ={ 3 val sqlContext = new SQLContext(sc) 4 val jdbcDF = sqlContext.read.format("jdbc").options(Map("url"->"jdbc:mysql://192.168.180.100:3306/bigdata","driver"->"com.mysql.jdbc.Driver","dbtable"->"person","user"->"root","password"->"123456")).load() 5 jdbcDF.show() 6 sc.stop() 7 }
再回寫到數據庫中
1 // 寫入數據庫 2 val personTextRdd = sc.textFile("D:\\data\\person.txt").map(_.split(" ")).map(x=>Row(x(0).toInt,x(1),x(2).toInt)) 3 4 val schema = StructType(List(StructField("id", IntegerType), StructField("name", StringType), StructField("age", IntegerType))) 5 6 val personDataFrame = sqlContext.createDataFrame(personTextRdd,schema) 7 8 val prop = new Properties() 9 prop.put("user","root") 10 prop.put("password","123456") 11 //寫入數據庫 12 personDataFrame.write.mode("append").jdbc("jdbc:mysql://192.168.180.100:3306/bigdata","bigdata.person",prop) 13 14 sc.stop()
