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