关注 spark技术分享,
撸spark源码 玩spark最佳实践

(obsolete) SQLContext

SQLContext

Caution

As of Spark 2.0.0 SQLContext is only for backward compatibility and is a mere wrapper of SparkSession.

In the pre-Spark 2.0’s ear, SQLContext was the entry point for Spark SQL. Whatever you did in Spark SQL it had to start from creating an instance of SQLContext.

A SQLContext object requires a SparkContext, a CacheManager, and a SQLListener. They are all transient and do not participate in serializing a SQLContext.

You should use SQLContext for the following:

Creating SQLContext Instance

You can create a SQLContext using the following constructors:

  • SQLContext(sc: SparkContext)
  • SQLContext.getOrCreate(sc: SparkContext)
  • SQLContext.newSession() allows for creating a new instance of SQLContext with a separate SQL configuration (through a shared SparkContext).

Setting Configuration Properties

You can set Spark SQL configuration properties using:

  • setConf(props: Properties): Unit
  • setConf(key: String, value: String): Unit

You can get the current value of a configuration property by key using:

  • getConf(key: String): String
  • getConf(key: String, defaultValue: String): String
  • getAllConfs: immutable.Map[String, String]
Note
Properties that start with spark.sql are reserved for Spark SQL.

Creating DataFrames

emptyDataFrame

emptyDataFrame creates an empty DataFrame. It calls createDataFrame with an empty RDD[Row] and an empty schema StructType(Nil).

createDataFrame for RDD and Seq

createDataFrame family of methods can create a DataFrame from an RDD of Scala’s Product types like case classes or tuples or Seq thereof.

createDataFrame for RDD of Row with Explicit Schema

This variant of createDataFrame creates a DataFrame from RDD of Row and explicit schema.

Registering User-Defined Functions (UDF)

udf method gives you access to UDFRegistration to manipulate user-defined functions. Functions registered using udf are available for Hive queries only.

Tip
Read up on UDFs in UDFs — User-Defined Functions document.

Caching DataFrames in In-Memory Cache

isCached method asks CacheManager whether tableName table is cached in memory or not. It simply requests CacheManager for CachedData and when exists, it assumes the table is cached.

You can cache a table in memory using cacheTable.

Caution
Why would I want to cache a table?

uncacheTable and clearCache remove one or all in-memory cached tables.

Implicits — SQLContext.implicits

The implicits object is a helper class with methods to convert objects into Datasets and DataFrames, and also comes with many Encoders for “primitive” types as well as the collections thereof.

Note

Import the implicits by import spark.implicits._ as follows:

It holds Encoders for Scala “primitive” types like Int, Double, String, and their collections.

It offers support for creating Dataset from RDD of any types (for which an encoder exists in scope), or case classes or tuples, and Seq.

It also offers conversions from Scala’s Symbol or $ to Column.

It also offers conversions from RDD or Seq of Product types (e.g. case classes or tuples) to DataFrame. It has direct conversions from RDD of Int, Long and String to DataFrame with a single column name _1.

Note
It is not possible to call toDF methods on RDD objects of other “primitive” types except Int, Long, and String.

Creating Datasets

createDataset family of methods creates a Dataset from a collection of elements of type T, be it a regular Scala Seq or Spark’s RDD.

It requires that there is an encoder in scope.

Note
Importing SQLContext.implicits brings many encoders available in scope.

Accessing DataFrameReader (read method)

The experimental read method returns a DataFrameReader that is used to read data from external storage systems and load it into a DataFrame.

Creating External Tables

The experimental createExternalTable family of methods is used to create an external table tableName and return a corresponding DataFrame.

Caution
FIXME What is an external table?

It assumes parquet as the default data source format that you can change using spark.sql.sources.default setting.

Dropping Temporary Tables

dropTempTable method drops a temporary table tableName.

Caution
FIXME What is a temporary table?

Creating Dataset[Long] (range method)

The range family of methods creates a Dataset[Long] with the sole id column of LongType for given start, end, and step.

Note
The three first variants use SparkContext.defaultParallelism for the number of partitions numPartitions.

Creating DataFrames for Table

table method creates a tableName table and returns a corresponding DataFrame.

Listing Existing Tables

table methods return a DataFrame that holds names of existing tables in a database.

The schema consists of two columns – tableName of StringType and isTemporary of BooleanType.

Note
tables is a result of SHOW TABLES [IN databaseName].

tableNames are similar to tables with the only difference that they return Array[String] which is a collection of table names.

Accessing StreamingQueryManager

The streams method returns a StreamingQueryManager that is used to…​TK

Caution
FIXME

Managing Active SQLContext for JVM

SQLContext.getOrCreate method returns an active SQLContext object for the JVM or creates a new one using a given sparkContext.

Note
It is a factory-like method that works on SQLContext class.

Interestingly, there are two helper methods to set and clear the active SQLContext object – setActive and clearActive respectively.

Executing SQL Queries

sql executes the sqlText SQL query.

Note
It supports Hive statements through HiveContext.

sql parses sqlText using a dialect that can be set up using spark.sql.dialect setting.

Note

sql is imported in spark-shell so you can execute Hive statements without spark prefix.

Tip
You may also use spark-sql shell script to interact with Hive.

Internally, it uses SessionState.sqlParser.parsePlan(sql) method to create a LogicalPlan.

Caution
FIXME Review

Tip

Enable INFO logging level for the loggers that correspond to the AbstractSqlParser to see what happens inside sql.

Add the following line to conf/log4j.properties:

Refer to Logging.

Creating New Session

You can use newSession method to create a new session without a cost of instantiating a new SqlContext from scratch.

newSession returns a new SqlContext that shares SparkContext, CacheManager, SQLListener, and ExternalCatalog.

Caution
FIXME Why would I need that?
赞(0) 打赏
未经允许不得转载:spark技术分享 » (obsolete) SQLContext
分享到: 更多 (0)

关注公众号:spark技术分享

联系我们联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏