@InterfaceStability.Stable public class SparkSession extends Object implements scala.Serializable, java.io.Closeable, Logging
In environments that this has been created upfront (e.g. REPL, notebooks), use the builder to get an existing session:
SparkSession.builder().getOrCreate()
The builder can also be used to create a new session:
SparkSession.builder
.master("local")
.appName("Word Count")
.config("spark.some.config.option", "some-value")
.getOrCreate()
param: sparkContext The Spark context associated with this Spark session. param: existingSharedState If supplied, use the existing shared state instead of creating a new one. param: parentSessionState If supplied, inherit all session state (i.e. temporary views, SQL config, UDFs etc) from parent.
Modifier and Type | Class and Description |
---|---|
static class |
SparkSession.Builder
Builder for
SparkSession . |
class |
SparkSession.implicits$
:: Experimental ::
(Scala-specific) Implicit methods available in Scala for converting
common Scala objects into
DataFrame s. |
Modifier and Type | Method and Description |
---|---|
Dataset<Row> |
baseRelationToDataFrame(BaseRelation baseRelation)
Convert a
BaseRelation created for external data sources into a DataFrame . |
static SparkSession.Builder |
builder()
Creates a
SparkSession.Builder for constructing a SparkSession . |
Catalog |
catalog()
Interface through which the user may create, drop, alter or query underlying
databases, tables, functions etc.
|
static void |
clearActiveSession()
Clears the active SparkSession for current thread.
|
static void |
clearDefaultSession()
Clears the default SparkSession that is returned by the builder.
|
void |
close()
Synonym for
stop() . |
RuntimeConfig |
conf()
Runtime configuration interface for Spark.
|
Dataset<Row> |
createDataFrame(JavaRDD<?> rdd,
Class<?> beanClass)
Applies a schema to an RDD of Java Beans.
|
Dataset<Row> |
createDataFrame(JavaRDD<Row> rowRDD,
StructType schema)
|
Dataset<Row> |
createDataFrame(java.util.List<?> data,
Class<?> beanClass)
Applies a schema to a List of Java Beans.
|
Dataset<Row> |
createDataFrame(java.util.List<Row> rows,
StructType schema)
:: DeveloperApi ::
Creates a
DataFrame from a java.util.List containing Row s using the given schema. |
Dataset<Row> |
createDataFrame(RDD<?> rdd,
Class<?> beanClass)
Applies a schema to an RDD of Java Beans.
|
<A extends scala.Product> |
createDataFrame(RDD<A> rdd,
scala.reflect.api.TypeTags.TypeTag<A> evidence$2)
:: Experimental ::
Creates a
DataFrame from an RDD of Product (e.g. |
Dataset<Row> |
createDataFrame(RDD<Row> rowRDD,
StructType schema)
|
<A extends scala.Product> |
createDataFrame(scala.collection.Seq<A> data,
scala.reflect.api.TypeTags.TypeTag<A> evidence$3)
:: Experimental ::
Creates a
DataFrame from a local Seq of Product. |
<T> Dataset<T> |
createDataset(java.util.List<T> data,
Encoder<T> evidence$6)
:: Experimental ::
Creates a
Dataset from a java.util.List of a given type. |
<T> Dataset<T> |
createDataset(RDD<T> data,
Encoder<T> evidence$5)
:: Experimental ::
Creates a
Dataset from an RDD of a given type. |
<T> Dataset<T> |
createDataset(scala.collection.Seq<T> data,
Encoder<T> evidence$4)
:: Experimental ::
Creates a
Dataset from a local Seq of data of a given type. |
Dataset<Row> |
emptyDataFrame()
Returns a
DataFrame with no rows or columns. |
<T> Dataset<T> |
emptyDataset(Encoder<T> evidence$1)
:: Experimental ::
Creates a new
Dataset of type T containing zero elements. |
ExperimentalMethods |
experimental()
:: Experimental ::
A collection of methods that are considered experimental, but can be used to hook into
the query planner for advanced functionality.
|
static scala.Option<SparkSession> |
getActiveSession()
Returns the active SparkSession for the current thread, returned by the builder.
|
static scala.Option<SparkSession> |
getDefaultSession()
Returns the default SparkSession that is returned by the builder.
|
SparkSession.implicits$ |
implicits()
Accessor for nested Scala object
|
ExecutionListenerManager |
listenerManager()
:: Experimental ::
An interface to register custom
QueryExecutionListener s
that listen for execution metrics. |
SparkSession |
newSession()
Start a new session with isolated SQL configurations, temporary tables, registered
functions are isolated, but sharing the underlying
SparkContext and cached data. |
Dataset<Long> |
range(long end)
:: Experimental ::
Creates a
Dataset with a single LongType column named id , containing elements
in a range from 0 to end (exclusive) with step value 1. |
Dataset<Long> |
range(long start,
long end)
:: Experimental ::
Creates a
Dataset with a single LongType column named id , containing elements
in a range from start to end (exclusive) with step value 1. |
Dataset<Long> |
range(long start,
long end,
long step)
:: Experimental ::
Creates a
Dataset with a single LongType column named id , containing elements
in a range from start to end (exclusive) with a step value. |
Dataset<Long> |
range(long start,
long end,
long step,
int numPartitions)
:: Experimental ::
Creates a
Dataset with a single LongType column named id , containing elements
in a range from start to end (exclusive) with a step value, with partition number
specified. |
DataFrameReader |
read()
Returns a
DataFrameReader that can be used to read non-streaming data in as a
DataFrame . |
DataStreamReader |
readStream()
Returns a
DataStreamReader that can be used to read streaming data in as a DataFrame . |
org.apache.spark.sql.internal.SessionState |
sessionState()
State isolated across sessions, including SQL configurations, temporary tables, registered
functions, and everything else that accepts a
SQLConf . |
static void |
setActiveSession(SparkSession session)
Changes the SparkSession that will be returned in this thread and its children when
SparkSession.getOrCreate() is called.
|
static void |
setDefaultSession(SparkSession session)
Sets the default SparkSession that is returned by the builder.
|
org.apache.spark.sql.internal.SharedState |
sharedState()
State shared across sessions, including the
SparkContext , cached data, listener,
and a catalog that interacts with external systems. |
SparkContext |
sparkContext() |
Dataset<Row> |
sql(String sqlText)
Executes a SQL query using Spark, returning the result as a
DataFrame . |
SQLContext |
sqlContext()
A wrapped version of this session in the form of a
SQLContext , for backward compatibility. |
void |
stop()
Stop the underlying
SparkContext . |
StreamingQueryManager |
streams()
:: Experimental ::
Returns a
StreamingQueryManager that allows managing all the
StreamingQuery s active on this . |
Dataset<Row> |
table(String tableName)
Returns the specified table/view as a
DataFrame . |
<T> T |
time(scala.Function0<T> f)
Executes some code block and prints to stdout the time taken to execute the block.
|
UDFRegistration |
udf()
A collection of methods for registering user-defined functions (UDF).
|
String |
version()
The version of Spark on which this application is running.
|
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
initializeLogging, initializeLogIfNecessary, isTraceEnabled, log_, log, logDebug, logDebug, logError, logError, logInfo, logInfo, logName, logTrace, logTrace, logWarning, logWarning
public static SparkSession.Builder builder()
SparkSession.Builder
for constructing a SparkSession
.
public static void setActiveSession(SparkSession session)
session
- (undocumented)public static void clearActiveSession()
public static void setDefaultSession(SparkSession session)
session
- (undocumented)public static void clearDefaultSession()
public static scala.Option<SparkSession> getActiveSession()
public static scala.Option<SparkSession> getDefaultSession()
public SparkContext sparkContext()
public String version()
public org.apache.spark.sql.internal.SharedState sharedState()
SparkContext
, cached data, listener,
and a catalog that interacts with external systems.
This is internal to Spark and there is no guarantee on interface stability.
public org.apache.spark.sql.internal.SessionState sessionState()
SQLConf
.
If parentSessionState
is not null, the SessionState
will be a copy of the parent.
This is internal to Spark and there is no guarantee on interface stability.
public SQLContext sqlContext()
SQLContext
, for backward compatibility.
public RuntimeConfig conf()
This is the interface through which the user can get and set all Spark and Hadoop
configurations that are relevant to Spark SQL. When getting the value of a config,
this defaults to the value set in the underlying SparkContext
, if any.
public ExecutionListenerManager listenerManager()
QueryExecutionListener
s
that listen for execution metrics.
public ExperimentalMethods experimental()
public UDFRegistration udf()
The following example registers a Scala closure as UDF:
sparkSession.udf.register("myUDF", (arg1: Int, arg2: String) => arg2 + arg1)
The following example registers a UDF in Java:
sparkSession.udf().register("myUDF",
(Integer arg1, String arg2) -> arg2 + arg1,
DataTypes.StringType);
public StreamingQueryManager streams()
StreamingQueryManager
that allows managing all the
StreamingQuery
s active on this
.
public SparkSession newSession()
SparkContext
and cached data.
SparkContext
, all shared state is initialized lazily.
This method will force the initialization of the shared state to ensure that parent
and child sessions are set up with the same shared state. If the underlying catalog
implementation is Hive, this will initialize the metastore, which may take some time.
public Dataset<Row> emptyDataFrame()
DataFrame
with no rows or columns.
public <T> Dataset<T> emptyDataset(Encoder<T> evidence$1)
Dataset
of type T containing zero elements.
evidence$1
- (undocumented)public <A extends scala.Product> Dataset<Row> createDataFrame(RDD<A> rdd, scala.reflect.api.TypeTags.TypeTag<A> evidence$2)
DataFrame
from an RDD of Product (e.g. case classes, tuples).
rdd
- (undocumented)evidence$2
- (undocumented)public <A extends scala.Product> Dataset<Row> createDataFrame(scala.collection.Seq<A> data, scala.reflect.api.TypeTags.TypeTag<A> evidence$3)
DataFrame
from a local Seq of Product.
data
- (undocumented)evidence$3
- (undocumented)public Dataset<Row> createDataFrame(RDD<Row> rowRDD, StructType schema)
DataFrame
from an RDD
containing Row
s using the given schema.
It is important to make sure that the structure of every Row
of the provided RDD matches
the provided schema. Otherwise, there will be runtime exception.
Example:
import org.apache.spark.sql._
import org.apache.spark.sql.types._
val sparkSession = new org.apache.spark.sql.SparkSession(sc)
val schema =
StructType(
StructField("name", StringType, false) ::
StructField("age", IntegerType, true) :: Nil)
val people =
sc.textFile("examples/src/main/resources/people.txt").map(
_.split(",")).map(p => Row(p(0), p(1).trim.toInt))
val dataFrame = sparkSession.createDataFrame(people, schema)
dataFrame.printSchema
// root
// |-- name: string (nullable = false)
// |-- age: integer (nullable = true)
dataFrame.createOrReplaceTempView("people")
sparkSession.sql("select name from people").collect.foreach(println)
rowRDD
- (undocumented)schema
- (undocumented)public Dataset<Row> createDataFrame(JavaRDD<Row> rowRDD, StructType schema)
DataFrame
from a JavaRDD
containing Row
s using the given schema.
It is important to make sure that the structure of every Row
of the provided RDD matches
the provided schema. Otherwise, there will be runtime exception.
rowRDD
- (undocumented)schema
- (undocumented)public Dataset<Row> createDataFrame(java.util.List<Row> rows, StructType schema)
DataFrame
from a java.util.List
containing Row
s using the given schema.
It is important to make sure that the structure of every Row
of the provided List matches
the provided schema. Otherwise, there will be runtime exception.
rows
- (undocumented)schema
- (undocumented)public Dataset<Row> createDataFrame(RDD<?> rdd, Class<?> beanClass)
WARNING: Since there is no guaranteed ordering for fields in a Java Bean, SELECT * queries will return the columns in an undefined order.
rdd
- (undocumented)beanClass
- (undocumented)public Dataset<Row> createDataFrame(JavaRDD<?> rdd, Class<?> beanClass)
WARNING: Since there is no guaranteed ordering for fields in a Java Bean, SELECT * queries will return the columns in an undefined order.
rdd
- (undocumented)beanClass
- (undocumented)public Dataset<Row> createDataFrame(java.util.List<?> data, Class<?> beanClass)
WARNING: Since there is no guaranteed ordering for fields in a Java Bean, SELECT * queries will return the columns in an undefined order.
data
- (undocumented)beanClass
- (undocumented)public Dataset<Row> baseRelationToDataFrame(BaseRelation baseRelation)
BaseRelation
created for external data sources into a DataFrame
.
baseRelation
- (undocumented)public <T> Dataset<T> createDataset(scala.collection.Seq<T> data, Encoder<T> evidence$4)
Dataset
from a local Seq of data of a given type. This method requires an
encoder (to convert a JVM object of type T
to and from the internal Spark SQL representation)
that is generally created automatically through implicits from a SparkSession
, or can be
created explicitly by calling static methods on Encoders
.
== Example ==
import spark.implicits._
case class Person(name: String, age: Long)
val data = Seq(Person("Michael", 29), Person("Andy", 30), Person("Justin", 19))
val ds = spark.createDataset(data)
ds.show()
// +-------+---+
// | name|age|
// +-------+---+
// |Michael| 29|
// | Andy| 30|
// | Justin| 19|
// +-------+---+
data
- (undocumented)evidence$4
- (undocumented)public <T> Dataset<T> createDataset(RDD<T> data, Encoder<T> evidence$5)
Dataset
from an RDD of a given type. This method requires an
encoder (to convert a JVM object of type T
to and from the internal Spark SQL representation)
that is generally created automatically through implicits from a SparkSession
, or can be
created explicitly by calling static methods on Encoders
.
data
- (undocumented)evidence$5
- (undocumented)public <T> Dataset<T> createDataset(java.util.List<T> data, Encoder<T> evidence$6)
Dataset
from a java.util.List
of a given type. This method requires an
encoder (to convert a JVM object of type T
to and from the internal Spark SQL representation)
that is generally created automatically through implicits from a SparkSession
, or can be
created explicitly by calling static methods on Encoders
.
== Java Example ==
List<String> data = Arrays.asList("hello", "world");
Dataset<String> ds = spark.createDataset(data, Encoders.STRING());
data
- (undocumented)evidence$6
- (undocumented)public Dataset<Long> range(long end)
Dataset
with a single LongType
column named id
, containing elements
in a range from 0 to end
(exclusive) with step value 1.
end
- (undocumented)public Dataset<Long> range(long start, long end)
Dataset
with a single LongType
column named id
, containing elements
in a range from start
to end
(exclusive) with step value 1.
start
- (undocumented)end
- (undocumented)public Dataset<Long> range(long start, long end, long step)
Dataset
with a single LongType
column named id
, containing elements
in a range from start
to end
(exclusive) with a step value.
start
- (undocumented)end
- (undocumented)step
- (undocumented)public Dataset<Long> range(long start, long end, long step, int numPartitions)
Dataset
with a single LongType
column named id
, containing elements
in a range from start
to end
(exclusive) with a step value, with partition number
specified.
start
- (undocumented)end
- (undocumented)step
- (undocumented)numPartitions
- (undocumented)public Catalog catalog()
public Dataset<Row> table(String tableName)
DataFrame
.
tableName
- is either a qualified or unqualified name that designates a table or view.
If a database is specified, it identifies the table/view from the database.
Otherwise, it first attempts to find a temporary view with the given name
and then match the table/view from the current database.
Note that, the global temporary view database is also valid here.public Dataset<Row> sql(String sqlText)
DataFrame
.
The dialect that is used for SQL parsing can be configured with 'spark.sql.dialect'.
sqlText
- (undocumented)public DataFrameReader read()
DataFrameReader
that can be used to read non-streaming data in as a
DataFrame
.
sparkSession.read.parquet("/path/to/file.parquet")
sparkSession.read.schema(schema).json("/path/to/file.json")
public DataStreamReader readStream()
DataStreamReader
that can be used to read streaming data in as a DataFrame
.
sparkSession.readStream.parquet("/path/to/directory/of/parquet/files")
sparkSession.readStream.schema(schema).json("/path/to/directory/of/json/files")
public <T> T time(scala.Function0<T> f)
f
- (undocumented)public SparkSession.implicits$ implicits()
public void stop()
SparkContext
.
public void close()
stop()
.
close
in interface java.io.Closeable
close
in interface AutoCloseable