SparkSQL簡介java
Spark SQL是Spark用來處理結構化數據的一個模塊,它提供了一個編程抽象叫作DataFrame而且做爲分佈式SQL查詢引擎的做用。它是將Spark SQL轉換成RDD,而後提交到集羣執行,執行效率很是快!node
SparkSQL的特性mysql
1.易整合
2.統一的數據訪問方式
3.兼容Hive
4.標準的數據鏈接sql
DataFrames簡介
與RDD相似,DataFrame也是一個分佈式數據容器。然而DataFrame更像傳統數據庫的二維表格,除了數據之外,還記錄數據的結構信息,即schema。同時,與Hive相似,DataFrame也支持嵌套數據類型(struct、array和map)。從API易用性的角度上 看,DataFrame API提供的是一套高層的關係操做,比函數式的RDD API要更加友好,門檻更低。因爲與R和Pandas的DataFrame相似,Spark DataFrame很好地繼承了傳統單機數據分析的開發體驗。shell
建立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://node1: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.showapache
DataFrames常見操做編程
1.//查看DataFrame中的內容
personDF.show
2.//查看DataFrame部分列中的內容
personDF.select(personDF.col("name")).show
personDF.select(col("name"), col("age")).show
personDF.select("name").show
3.//打印DataFrame的Schema信息
personDF.printSchema
4.//查詢全部的name和age,並將age+1
personDF.select(col("id"), col("name"), col("age") + 1).show
personDF.select(personDF("id"), personDF("name"), personDF("age") + 1).show
5.//過濾age大於等於18的
personDF.filter(col("age") >= 18).show
6.//按年齡進行分組並統計相同年齡的人數
personDF.groupBy("age").count().show()json
使用SparkSQL風格
若是想使用SQL風格的語法,須要將DataFrame註冊成表
personDF.registerTempTable("t_person")app
1.//查詢年齡最大的前兩名
sqlContext.sql("select * from t_person order by age desc limit 2").show
2.//顯示錶的Schema信息
sqlContext.sql("desc t_person").show
sqlContext.sql()中的內容和寫普通的基本一致,可是要注意SparkSQL不支持子查詢
編寫程序執行SparkSQL語句
1.首先在maven項目的pom.xml中添加Spark SQL的依賴
<dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-sql_2.10</artifactId> <version>1.5.2</version> </dependency>
2.具體寫法1使用case class
import org.apache.spark.{SparkConf, SparkContext} import org.apache.spark.sql.SQLContext object InferringSchema { def main(args: Array[String]) { //建立SparkConf()並設置App名稱 val conf = new SparkConf().setAppName("SQL-1") //SQLContext要依賴SparkContext val sc = new SparkContext(conf) //建立SQLContext val sqlContext = new SQLContext(sc) //從指定的地址建立RDD val lineRDD = sc.textFile(args(0)).map(_.split(" ")) //建立case class //將RDD和case class關聯 val personRDD = lineRDD.map(x => Person(x(0).toInt, x(1), x(2).toInt)) //導入隱式轉換,若是不到人沒法將RDD轉換成DataFrame //將RDD轉換成DataFrame import sqlContext.implicits._ val personDF = personRDD.toDF //註冊表 personDF.registerTempTable("t_person") //傳入SQL val df = sqlContext.sql("select * from t_person order by age desc limit 2") //將結果以JSON的方式存儲到指定位置 df.write.json(args(1)) //中止Spark Context sc.stop() } } //case class必定要放到外面 case class Person(id: Int, name: String, age: Int)
將程序打成jar包,上傳到spark集羣,提交Spark任務
/usr/local/spark-1.5.2-bin-hadoop2.6/bin/spark-submit
--class spark.sql.InferringSchema
--master spark://node1:7077
/root/spark-mvn-1.0-SNAPSHOT.jar
hdfs://node1:9000/person.txt
hdfs://node1:9000/out
查看運行結果
hdfs dfs -cat hdfs://node1:9000/out/part-r-*
3.具體寫法2,經過StructType直接指定Schema
import org.apache.spark.sql.{Row, SQLContext} import org.apache.spark.sql.types._ import org.apache.spark.{SparkContext, SparkConf} object SpecifyingSchema { def main(args: Array[String]) { //建立SparkConf()並設置App名稱 val conf = new SparkConf().setAppName("SQL-2") //SQLContext要依賴SparkContext val sc = new SparkContext(conf) //建立SQLContext val sqlContext = new SQLContext(sc) //從指定的地址建立RDD val personRDD = sc.textFile(args(0)).map(_.split(" ")) //經過StructType直接指定每一個字段的schema val schema = StructType( List( StructField("id", IntegerType, true), StructField("name", StringType, true), StructField("age", IntegerType, true) ) ) //將RDD映射到rowRDD val rowRDD = personRDD.map(p => Row(p(0).toInt, p(1).trim, p(2).toInt)) //將schema信息應用到rowRDD上 val personDataFrame = sqlContext.createDataFrame(rowRDD, schema) //註冊表 personDataFrame.registerTempTable("t_person") //執行SQL val df = sqlContext.sql("select * from t_person order by age desc limit 4") //將結果以JSON的方式存儲到指定位置 df.write.json(args(1)) //中止Spark Context sc.stop() } }
從MySQL中加載數據(Spark Shell方式)
1.啓動Spark Shell,必須指定mysql鏈接驅動jar包
/usr/local/spark-1.5.2-bin-hadoop2.6/bin/spark-shell
--master spark://node1:7077
--jars /usr/local/spark-1.5.2-bin-hadoop2.6/mysql-connector-java-5.1.35-bin.jar
--driver-class-path /usr/local/spark-1.5.2-bin-hadoop2.6/mysql-connector-java-5.1.35-bin.jar
2.從mysql中加載數據
val jdbcDF = sqlContext.read.format("jdbc").options(Map("url" -> "jdbc:mysql://XXX:3306/bigdata", "driver" -> "com.mysql.jdbc.Driver", "dbtable" -> "person", "user" -> "root", "password" -> "123456")).load()
3.執行查詢
jdbcDF.show()
將數據寫入到MySQL中
import java.util.Properties import org.apache.spark.sql.{SQLContext, Row} import org.apache.spark.sql.types.{StringType, IntegerType, StructField, StructType} import org.apache.spark.{SparkConf, SparkContext} object JdbcRDD { def main(args: Array[String]) { val conf = new SparkConf().setAppName("MySQL-Demo") val sc = new SparkContext(conf) val sqlContext = new SQLContext(sc) //經過並行化建立RDD val personRDD = sc.parallelize(Array("1 tom 5", "2 jerry 3", "3 kitty 6")).map(_.split(" ")) //經過StructType直接指定每一個字段的schema val schema = StructType( List( StructField("id", IntegerType, true), StructField("name", StringType, true), StructField("age", IntegerType, true) ) ) //將RDD映射到rowRDD val rowRDD = personRDD.map(p => Row(p(0).toInt, p(1).trim, p(2).toInt)) //將schema信息應用到rowRDD上 val personDataFrame = sqlContext.createDataFrame(rowRDD, schema) //建立Properties存儲數據庫相關屬性 val prop = new Properties() prop.put("user", "root") prop.put("password", "123456") //將數據追加到數據庫 personDataFrame.write.mode("append").jdbc("jdbc:mysql://192.168.10.1:3306/bigdata", "bigdata.person", prop) //中止SparkContext sc.stop() } }
hive on spark-SQL
1.安裝hive,修改元數據庫,加上hive-site.xml(mysql鏈接) 2.將hive-site.xml文件拷貝到spark集羣的conf下 3.將mysql.jar拷貝到spark.lib下 4.執行:sqlCOntext.sql("select * from table1").show() .write.mode("append") .jdbc() .foreachPartition(it=>{ 1.初始化鏈接 2.it.map(x=>{ 寫數據到存儲層 }) 3.關鏈接 })