How do you create a SparkSession in PySpark?
Instruction: Provide a code snippet to demonstrate how to initialize a SparkSession in PySpark.
Updated
Use SparkSession.builder to configure and obtain a session. This standalone local example owns its session and stops it after use:
from pyspark.sql import SparkSession
spark = (SparkSession.builder.master("local[2]")
.appName("SessionExample")
.config("spark.sql.shuffle.partitions", "2")
.getOrCreate())
try:
assert spark.range(3).count() == 3
finally:
spark.stop()
local[2] uses two local worker threads for a small test; it is not a production cluster size. For cluster deployment, supply the master and deployment resources through the deployment mechanism, such as spark-submit, rather than hard-coding this local setting.
getOrCreate() may return an existing session. Builder options can affect that session where supported, but do not resize an already running executor fleet or replace its SparkContext. In a notebook or managed environment, reuse the supplied spark session and let its owner manage shutdown. Session builder behavior
Use real documented configuration keys, match Python/JDK/Spark compatibility, and distinguish a classic local session from a remote Spark Connect session. An arbitrary placeholder .config key is not a working resource-tuning example.