Spark SQL是spark用來處理結構化數據的
Spark中所有功能的入口點都是SparkSession
類。要創建基本的SparkSession
,只需使用SparkSession.builder()
:
import org.apache.spark.sql.SparkSession
val spark = SparkSession
。builder ()
。appName (“Spark SQL基本示例” )
。config (“spark.some.config.option” , “some-value” )
。getOrCreate ()
//對於將RDD轉換爲DataFrames等隱式轉換,請
導入 spark.implicits._
①Creating DataFrames:
使用 SparkSession
,應用程序可以從現有的RDD
,Hive表或Spark數據源創建DataFrame 。
作爲示例,以下內容基於JSON文件的內容創建DataFrame:
val df = spark.read.json("examples/src/main/resources/people.json")
df.show() // +----+-------+ // | age| name| // +----+-------+ // |null|Michael| // | 30| Andy| // | 19| Justin| // +----+-------+
②創建好DataFrame的操作,接下來是關於DataFrame的操作:
// This import is needed to use the $-notation import spark.implicits._ // Print the schema in a tree format df.printSchema() // root // |-- age: long (nullable = true) // |-- name: string (nullable = true) // Select only the "name" column df.select("name").show() // +-------+ // | name| // +-------+ // |Michael| // | Andy| // | Justin| // +-------+ // Select everybody, but increment the age by 1 df.select($"name", $"age" + 1).show() // +-------+---------+ // | name|(age + 1)| // +-------+---------+ // |Michael| null| // | Andy| 31| // | Justin| 20| // +-------+---------+ // Select people older than 21 df.filter($"age" > 21).show() // +---+----+ // |age|name| // +---+----+ // | 30|Andy| // +---+----+ // Count people by age df.groupBy("age").count().show() // +----+-----+ // | age|count| // +----+-----+ // | 19| 1| // |null| 1| // | 30| 1| // +----+-----+
③Sql方式運行
// 將DataFrame註冊爲一個臨時表 df.createOrReplaceTempView("people") //執行sql,返回DataFrame的類型數據 val sqlDF = spark.sql("SELECT * FROM people") sqlDF.show() // +----+-------+ // | age| name| // +----+-------+ // |null|Michael| // | 30| Andy| // | 19| Justin| // +----+-------+
Spark SQL中的臨時視圖是會話範圍的,如果創建它的會話終止,它將消失。如果您希望擁有一個在所有會話之間共享的臨時視圖並保持活動狀態,直到Spark應用程序終止,您可以創建一個全局臨時視圖。全局臨時視圖與系統保留的數據庫綁定global_temp
,我們必須使用限定名稱來引用它,例如SELECT * FROM global_temp.view1
。
// Register the DataFrame as a global temporary view df.createGlobalTempView("people") // Global temporary view is tied to a system preserved database `global_temp` spark.sql("SELECT * FROM global_temp.people").show() // +----+-------+ // | age| name| // +----+-------+ // |null|Michael| // | 30| Andy| // | 19| Justin| // +----+-------+ // Global temporary view is cross-session spark.newSession().sql("SELECT * FROM global_temp.people").show() // +----+-------+ // | age| name| // +----+-------+ // |null|Michael| // | 30| Andy| // | 19| Justin| // +----+-------+
注: 臨時表在查詢的時候可以不用寫庫,全局表必須在之前加上global_temp.view1