作者:周志湖
1. SQLContext的创建
SQLContext是Spark SQL进行结构化数据处理的入口,可以通过它进行DataFrame的创建及SQL的执行,其创建方式如下:
//sc为SparkContext
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
其对应的源码为:
def this(sparkContext: SparkContext) = {
this(sparkContext, new CacheManager, SQLContext.createListenerAndUI(sparkContext), true)
}
其调用的是私有的主构造函数:
//1.主构造器中的参数CacheManager用于缓存查询结果
//在进行后续查询时会自动读取缓存中的数据
//2.SQLListener用于监听Spark scheduler事件,它继承自SparkListener
//3.isRootContext表示是否是根SQLContext
class SQLContext private[sql](
@transient val sparkContext: SparkContext,
@transient protected[sql] val cacheManager: CacheManager,
@transient private[sql] val listener: SQLListener,
val isRootContext: Boolean)
extends org.apache.spark.Logging with Serializable {
当spark.sql.allowMultipleContexts设置为true时,则允许创建多个SQLContexts/HiveContexts,创建方法为newSession
def newSession(): SQLContext = {
new SQLContext(
sparkContext = sparkContext,
cacheManager = cacheManager,
listener = listener,
isRootContext = false)
}
其isRootContext 被设置为false,否则会抛出异常,因为root SQLContext只能有一个,其它SQLContext与root SQLContext共享SparkContext, CacheManager, SQLListener。如果spark.sql.allowMultipleContexts为false,则只允许一个SQLContext存在
2. 核心成员变量 ——catalog
protected[sql] lazy val catalog: Catalog = new SimpleCatalog(conf)
catalog用于注销表、注销表、判断表是否存在等,例如当DataFrame调用registerTempTable 方法时
val people = sc.textFile("examples/src/main/resources/people.txt").map(_.split(","))