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()