Spark修炼之道(高级篇)——Spark源代码阅读:第十二节 Spark SQL 处理流程分析
作者:周志湖
以下的代码演示了通过Case Class进行表Schema定义的样例:
// sc is an existing SparkContext.
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
// this is used to implicitly convert an RDD to a DataFrame.
import sqlContext.implicits._
// Define the schema using a case class.
// Note: Case classes in Scala 2.10 can support only up to 22 fields. To work around this limit,
// you can use custom classes that implement the Product interface.
case class Person(name: String, age: Int)
// Create an RDD of Person objects and register it as a table.
val people = sc.textFile("examples/src/main/resources/people.txt").map(_.split(",")).map(p => Person(p(0), p(1).trim.toInt)).toDF()
people.registerTempTable("people")
// SQL statements can be run by using the sql methods provided by sqlContext.
val teenagers = sqlContext.sql("SELECT name, age FROM people WHERE age >= 13 AND age <= 19")
// The results of SQL queries are DataFrames and support all the normal RDD operations.
// The columns of a row in the result can be accessed by field index:
teenagers.map(t => "Name: " + t(0)).collect().foreach(println)
// or by field name:
teenagers.map(t => "Name: " + t.getAs[String]("name")).collect().foreach(println)
// row.getValuesMap[T] retrieves multiple columns at once into a Map[String, T]
teenagers.map(_.getValuesMap[Any](List("name", "age"))).collect().foreach(println)
// Map("name" -> "Justin", "age" -> 19)
(1)sql方法返回DataFrame
def sql(sqlText: String): DataFrame = {
DataFrame(this, parseSql(sqlText))
}
当中parseSql(sqlText)方法生成对应的LogicalPlan得到,该方法源代码例如以下:
//依据传入的sql语句,生成LogicalPlan
protected[sql] def parseSql(sql: String): LogicalPlan = ddlParser.parse(sql, false)
ddlParser对象定义例如以下:
protected[sql] val sqlParser = new SparkSQLParser(getSQLDialect().parse(_))
protected[sql] val ddlParser = new DDLParser(sqlParser.parse(_))
(2)然后调用DataFrame的apply方法
private[sql] object DataFrame {
def apply(sqlContext: SQLContext, logicalPlan: LogicalPlan): DataFrame = {
new DataFrame(sqlContext, logicalPlan)
}
}
能够看到,apply方法參数有两个,各自是SQLContext和LogicalPlan,调用的是DataFrame的构造方法,详细源代码例如以下:
//DataFrame构造方法。该构造方法会自己主动对LogicalPlan进行分析,然后返回QueryExecution对象
def this(sqlContext: SQLContext, logicalPlan: LogicalPlan) = {
this(sqlContext, {
val qe = sqlContext.executePlan(logicalPlan)
//推断是否已经创建。假设是则抛异常
if (sqlContext.conf.dataFrameEagerAnalysis) {
qe.assertAnalyzed() // This should force analysis and throw errors if there are any
}
qe
})
}
(3)val qe = sqlContext.executePlan(logicalPlan) 返回QueryExecution, sqlContext.executePlan方法源代码例如以下:
protected[sql] def executePlan(plan: LogicalPlan) =
new sparkexecution.QueryExecution(this, plan)
QueryExecution类中表达了Spark运行SQL的主要工作流程,详细例如以下
class QueryExecution(val sqlContext: SQLContext, val logical: LogicalPlan) {
@VisibleForTesting
def assertAnalyzed(): Unit = sqlContext.analyzer.checkAnalysis(analyzed)
lazy val analyzed: LogicalPlan = sqlContext.analyzer.execute(logical)
lazy val withCachedData: LogicalPlan = {
assertAnalyzed()
sqlContext.cacheManager.useCachedData(analyzed)
}
lazy val optimizedPlan: LogicalPlan = sqlContext.optimizer.execute(withCachedData)
// TODO: Don't just pick the first one...
lazy val sparkPlan: SparkPlan = {
SparkPlan.currentContext.set(sqlContext)
sqlContext.planner.plan(optimizedPlan).next()
}
// executedPlan should not be used to initialize any SparkPlan. It should be
// only used for execution.
lazy val executedPlan: SparkPlan = sqlContext.prepareForExecution.execute(sparkPlan)
/** Internal version of the RDD. Avoids copies and has no schema */
//调用toRDD方法运行任务将结果转换为RDD
lazy val toRdd: RDD[InternalRow] = executedPlan.execute()
protected def stringOrError[A](f: => A): String =
try f.toString catch { case e: Throwable => e.toString }
def simpleString: String = {
s"""== Physical Plan ==
|${stringOrError(executedPlan)}
""".stripMargin.trim
}
override def toString: String = {
def output =
analyzed.output.map(o => s"${o.name}: ${o.dataType.simpleString}").mkString(", ")
s"""== Parsed Logical Plan ==
|${stringOrError(logical)}
|== Analyzed Logical Plan ==
|${stringOrError(output)}
|${stringOrError(analyzed)}
|== Optimized Logical Plan ==
|${stringOrError(optimizedPlan)}
|== Physical Plan ==
|${stringOrError(executedPlan)}
|Code Generation: ${stringOrError(executedPlan.codegenEnabled)}
""".stripMargin.trim
}
}
能够看到,SQL的运行流程为
1.Parsed Logical Plan:LogicalPlan
2.Analyzed Logical Plan:
lazy val analyzed: LogicalPlan = sqlContext.analyzer.execute(logical)
3.Optimized Logical Plan:lazy val optimizedPlan: LogicalPlan = sqlContext.optimizer.execute(withCachedData)
4. Physical Plan:lazy val executedPlan: SparkPlan = sqlContext.prepareForExecution.execute(sparkPlan)
能够调用results.queryExecution方法查看,代码例如以下:
scala> results.queryExecution
res1: org.apache.spark.sql.SQLContext#QueryExecution =
== Parsed Logical Plan ==
'Project [unresolvedalias('name)]
'UnresolvedRelation [people], None
== Analyzed Logical Plan ==
name: string
Project [name#0]
Subquery people
LogicalRDD [name#0,age#1], MapPartitionsRDD[4] at createDataFrame at <console>:47
== Optimized Logical Plan ==
Project [name#0]
LogicalRDD [name#0,age#1], MapPartitionsRDD[4] at createDataFrame at <console>:47
== Physical Plan ==
TungstenProject [name#0]
Scan PhysicalRDD[name#0,age#1]
Code Generation: true
(4) 然后调用DataFrame的主构造器完毕DataFrame的构造
class DataFrame private[sql](
@transient val sqlContext: SQLContext,
@DeveloperApi @transient val queryExecution: QueryExecution) extends Serializable
(5)
当调用DataFrame的collect等方法时,便会触发运行executedPlan
def collect(): Array[Row] = withNewExecutionId {
queryExecution.executedPlan.executeCollect()
}
比如:
scala> results.collect
res6: Array[org.apache.spark.sql.Row] = Array([Michael], [Andy], [Justin])
总体流程图例如以下:
Spark修炼之道(高级篇)——Spark源代码阅读:第十二节 Spark SQL 处理流程分析的更多相关文章
- Spark修炼之道——Spark学习路线、课程大纲
课程内容 Spark修炼之道(基础篇)--Linux基础(15讲).Akka分布式编程(8讲) Spark修炼之道(进阶篇)--Spark入门到精通(30讲) Spark修炼之道(实战篇)--Spar ...
- 【转】【技术博客】Spark性能优化指南——高级篇
http://mp.weixin.qq.com/s?__biz=MjM5NjQ5MTI5OA==&mid=2651745207&idx=1&sn=3d70d59cede236e ...
- Spark性能优化指南——高级篇
本文转载自:https://tech.meituan.com/spark-tuning-pro.html 美团技术点评团队) Spark性能优化指南——高级篇 李雪蕤 ·2016-05-12 14:4 ...
- Spark性能优化指南-高级篇(spark shuffle)
Spark性能优化指南-高级篇(spark shuffle) 非常好的讲解
- Spark修炼之道(进阶篇)——Spark入门到精通:第九节 Spark SQL执行流程解析
1.总体执行流程 使用下列代码对SparkSQL流程进行分析.让大家明确LogicalPlan的几种状态,理解SparkSQL总体执行流程 // sc is an existing SparkCont ...
- 【转载】Spark性能优化指南——高级篇
前言 数据倾斜调优 调优概述 数据倾斜发生时的现象 数据倾斜发生的原理 如何定位导致数据倾斜的代码 查看导致数据倾斜的key的数据分布情况 数据倾斜的解决方案 解决方案一:使用Hive ETL预处理数 ...
- Spark性能优化指南——高级篇(转载)
前言 继基础篇讲解了每个Spark开发人员都必须熟知的开发调优与资源调优之后,本文作为<Spark性能优化指南>的高级篇,将深入分析数据倾斜调优与shuffle调优,以解决更加棘手的性能问 ...
- Spark性能优化指南-高级篇
转自https://tech.meituan.com/spark-tuning-pro.html,感谢原作者的贡献 前言 继基础篇讲解了每个Spark开发人员都必须熟知的开发调优与资源调优之后,本文作 ...
- Spark性能调优-高级篇
前言 继基础篇讲解了每个Spark开发人员都必须熟知的开发调优与资源调优之后,本文作为<Spark性能优化指南>的高级篇,将深入分析数据倾斜调优与shuffle调优,以解决更加棘手的性能问 ...
随机推荐
- H5发起微信支付
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- javascript的var声明变量和不用var声明变量在全局作用域的区别;
在全局作用域下,使用var定义的变量不可以delete,没有var 定义的变量可以delete.也就说明隐含全局变量严格来说不是真正的变量,而是全局对象的属性,因为属性可以通过delete删除,而变量 ...
- linux VNC-server
[root@kvm-server Packages]# rpm -qpi tigervnc-server-1.8.0-1.el7.x86_64.rpm Name : tigervnc-server V ...
- 紫书 习题 11-15 UVa 1668 (图论构造法)
参考了http://www.bubuko.com/infodetail-1276416.html 首先是逆向思维, 向把每条边看作一条路径, 然后再去合并 然后我们讨论怎么样合并时最优的 我们讨论当前 ...
- EEPlat PaaS中的多租户数据隔离模式
EEPlat PaaS支持三种租户的数据隔离技术:Sparce Column.tenantId字段隔离.每一个租户独立数据库. 1)Sparce Column,和Salesforce Appforce ...
- 与Greenplum度过的三个星期
5月4日-5月24日.断断续续折腾了三个星期的Greenplum,总算告一段落了:扩容,发现扩不成容.仅仅好升级.升级,发现一堆错误,仅仅好暂停修复数据库:修好了,继续升级.升完级,发现错误.修啊修啊 ...
- OCP-1Z0-051-题目解析-第50题
50. SLS is a private synonym for the SH.SALES table. The user SH issues the following command: DRO ...
- 转发真阿当老师的一片文章 受益匪浅 (出处:http://cly84920.blog.163.com/blog/static/24750013320158203575958/)
忽悠程序员做一辈子程序员,以白胡子白头发hacker为目标的人有两种: 1,自己不写程序,但需要有将才为自己打下手的人,这种人往往看他资质和勤奋均平平,却成了你领导.别不服,这种人虽不见得有帅才的能力 ...
- Logical Operators (Transact-SQL)
https://docs.microsoft.com/en-us/sql/t-sql/language-elements/logical-operators-transact-sql Logical ...
- 使用CSS3制作网站常用的小三角形
现在在前端开发中,经常会看到一些小三角形,如一些导航的下拉菜单,还有一些聊天信息的气泡模式,很多时候我们都是通过切图片的方法来制作,今天零度给大家分享一个完全通过css3实现的小三角效果. 先上htm ...