如何更新现有 SparkSession 实例或在 spark-shell 中创建一个新实例?

Mar*_*kus 3 scala apache-spark apache-spark-sql

当我启动时spark-shell,它会创建一个SparkSession. 但是,我应该按如下方式创建它:

val spark = SparkSession.builder()
                        .config("es.nodes",elasticHost)
                        .config("es.port",elasticPort)
                        .config("es.nodes.wan.only","true")
                        .appName("Test")
                        .getOrCreate()
Run Code Online (Sandbox Code Playgroud)

如上所示,如何更新现有sparkspark-shell或创建新的?

Jac*_*ski 6

您可以通过设置配置属性SparkSession.conf.set或创建另一个SparkSession使用实例SparkSession.newSession,然后设置属性。

set(key: String, value: String): Unit设置给定的 Spark 运行时配置属性。

newSession():SparkSession启动一个新的会话,SQL 配置隔离,临时表、注册函数是隔离的,但共享底层 SparkContext 和缓存数据。

两种方式的工作方式(几乎)相同,区别在于您可以临时将属性设置为新值并SparkSession同时使用两者。

// hello property is not set
scala> spark.conf.getOption("hello")
res1: Option[String] = None

scala> spark.conf.set("hello", "world")

// hello property is set
scala> spark.conf.getOption("hello")
res3: Option[String] = Some(world)

// create a new SparkSession (so you'll have two at the same time)
val ns = spark.newSession

// hello is not set in a new session
scala> ns.conf.getOption("hello")
res4: Option[String] = None

ns.conf.set("hello", "hello in another session")

scala> ns.conf.getOption("hello")
res8: Option[String] = Some(hello in another session)

// the value of hello in the initial SparkSession remains unchanged
scala> spark.conf.getOption("hello")
res9: Option[String] = Some(world)
Run Code Online (Sandbox Code Playgroud)