Sub topic 2
The spark session you already have
This chapter explains the spark object that every Databricks notebook provides, what it does, and the mistakes people make with it. It assumes you can write basic Python or SQL, understand tabular data (rows, columns, types), and can attach a notebook to compute in a Databricks workspace.
What `spark` is
When you attach a notebook to compute and run a cell, a variable named spark already exists. It is a SparkSession, the entry point for working with Spark's DataFrame and SQL APIs. You do not create it, and you do not need to configure it to start.
You can check this in any cell:
print(type(spark))
print(spark.version)The first line prints the session class. The second prints the Spark version of the attached compute. On serverless compute and on Databricks Connect, the class can differ from the classic one, but the methods you use in this tutorial behave the same way.
Databricks creates the session for you because the notebook is already attached to a running cluster or serverless environment. The session is your handle to that compute. Everything you ask for through spark is planned by the driver and run by the executors.
What the session gives you
Most of your work starts from a few members of spark.
| Member | What it does | Example |
|---|---|---|
| `spark.read` | Builds a reader that loads files or tables into a DataFrame | `spark.read.table("main.default.orders")` |
| `spark.createDataFrame` | Builds a DataFrame from local Python data | `spark.createDataFrame(rows, schema)` |
| `spark.sql` | Runs a SQL query and returns a DataFrame | `spark.sql("SELECT 1 AS x")` |
| `spark.table` | Returns a registered table or view as a DataFrame | `spark.table("orders_v")` |
| `spark.range` | Creates a DataFrame with a single `id` column of numbers | `spark.range(1000)` |
| `spark.conf` | Reads and sets session-level configuration | `spark.conf.get("spark.sql.shuffle.partitions")` |
| `spark.catalog` | Lists and manages catalogs, databases, tables and temporary views | `spark.catalog.listTables()` |
Each of these returns either a DataFrame or a small object that produces one. A DataFrame always belongs to the session that created it. That tie is the reason temporary views, covered below, are visible only inside one session.
Your first DataFrame from the session
spark.range is a quick way to get a DataFrame without any data files:
numbers = spark.range(5)
numbers.printSchema()
numbers.show()The output has one column named id of type long, holding the values 0 to 4. Nothing here read a file. The session generated the rows itself.
You can also build one from Python data with a DDL-style schema string:
people = spark.createDataFrame(
[(1, "alice"), (2, "bob")],
"id INT, name STRING",
)
people.show()A DDL-style schema string lists each column name and its type, separated by commas. It is shorter than building StructType objects by hand, and it gives you the exact types you want instead of guessed ones.
How the session relates to the driver and the cluster
The Python code in your notebook runs on the driver, which is one machine in the cluster. The spark object lives there. When you write DataFrame code, Python does not process the rows itself. It builds a description of the work and hands it to Spark, which splits the work into tasks for the executors.
Two consequences follow from this model.
- Plain Python variables, such as lists and dictionaries, live only on the driver. Executors do not see them unless Spark ships them along with a task.
- A DataFrame variable does not hold the rows. It holds a plan. Later chapters on lazy evaluation explain this in detail. For now, remember that creating a DataFrame variable is cheap, and the work happens when you ask for a result.
Session configuration
spark.conf reads and changes settings for the current session. Settings you change this way apply only to your session and do not alter the cluster.
print(spark.conf.get("spark.sql.shuffle.partitions"))
spark.conf.set("spark.sql.shuffle.partitions", "64")
print(spark.conf.get("spark.sql.shuffle.partitions"))spark.sql.shuffle.partitions sets how many partitions Spark uses after a shuffle, which is a redistribution of data across the cluster. The first line prints the current value. The second sets a new one. Values are passed as strings.
Some points to know:
- Not every setting can be changed at runtime. Settings that are fixed when the cluster starts, such as executor memory, must be set in the cluster configuration. Setting them with
spark.conf.seteither fails or has no effect. - Serverless compute allows only a limited set of session settings. If
spark.conf.setraises an error for a property, check whether your compute type supports it. - Many Databricks defaults, such as adaptive query execution, are already tuned. Change a setting only when you can measure the effect.
Temporary views belong to the session
Calling createOrReplaceTempView registers a DataFrame under a name in the current session:
people.createOrReplaceTempView("people_v")
spark.sql("SELECT name FROM people_v WHERE id = 2").show()The view is visible to spark.sql and to SQL cells in the same notebook, because they share the session. It disappears when the session ends. Another notebook, even on the same cluster, does not see it, because each notebook gets its own session on the shared compute.
Common errors
Creating your own session
Code copied from tutorials often starts with this:
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("demo").getOrCreate()In a Databricks notebook this is unnecessary. getOrCreate() returns the existing session, so it usually does no harm, but any configuration you pass to the builder may be ignored. Delete the line and use the spark that is already there. Never call spark.stop(). It can end the session your notebook depends on and force you to detach and reattach.
Name collisions
spark is an ordinary Python variable, so you can overwrite it:
spark = "oops"After this, spark.read fails with an AttributeError, because a string has no read attribute. Detaching and reattaching the notebook, or restarting the Python process, restores the session. Avoid naming your own variables spark, sc or dbutils.
Session state after a restart
Temporary views, session configuration changes and Python variables are all lost when the Python process restarts or the notebook is detached. Cells that depended on them then fail with errors such as Table or view not found. Rerun the cells from the top to rebuild that state. Anything you want to keep must be written to a table, which a later chapter covers.
Expecting `spark` to work outside the notebook
A standalone Python script run on your laptop has no spark variable. Databricks Connect and jobs create sessions in their own ways. Code that relies on the notebook's global spark may need a small change before it runs there.
Summary of what to remember
sparkis a ready-madeSparkSession. Use it directly.- It is the starting point for reading data, building DataFrames and running SQL.
- It lives on the driver and plans work that executors perform.
- Settings and temporary views are tied to the session and vanish when it ends.
Exercise
A teammate's notebook begins with spark = SparkSession.builder.appName("etl").config("spark.executor.memory", "8g").getOrCreate(). They say it sets executor memory to 8 GB. Is that correct, and what should they do instead?
Show answer
It is not reliable. A Databricks notebook already has a session attached to running compute, so getOrCreate() returns that session, and executor memory is fixed when the cluster starts. The teammate should remove the line, use the existing spark, and set executor memory in the cluster configuration (or choose a larger node type).
Exercise
You run people.createOrReplaceTempView("people_v") in notebook A. In notebook B, attached to the same cluster, spark.sql("SELECT * FROM people_v") fails. Why, and how could you share the data?
Show answer
Each notebook has its own session, and a temporary view exists only in the session that created it. To share the data, write the DataFrame to a table with people.write.saveAsTable("catalog.schema.people"), and read it from notebook B with spark.table("catalog.schema.people").