【背景】
Spark腳本中可以通過sparkContext.sql("xxxx")的方式直接調用SQL代碼,但其限制是處理的表必須是在spark context中已註冊的臨時表。臨時表不會佔用額外內存,可以理解爲是對內存空間重新命名了一下而已。
【臨時表的創建】
// 創建它的SparkSession對象終止前有效
df.createOrReplaceTempView("tempViewName")
// spark應用程序終止前有效
df.createOrReplaceGlobalTempView("tempViewName")
【臨時表的註銷】
spark.catalog.dropTempView("tempViewName")
spark.catalog.dropGlobalTempView("tempViewName")
【臨時表的使用例子】
package high_quality._history
import org.apache.log4j.{Level, Logger}
import org.apache.spark.sql.SparkSession
object test {
def main(args: Array[String]) {
Logger.getRootLogger.setLevel(Level.ERROR)
val spark = SparkSession.builder().master("local[*]").getOrCreate()
import spark.implicits._
// 構造一個DataFrame
val df = Seq("1").toDF("value")
// 註冊一個臨時表
df.createOrReplaceTempView("tmp_table")
// 通過spark SQL使用該臨時表
val ret = spark.sql("SELECT * FROM tmp_table")
ret.show()
}
}