This is an automated email from the ASF dual-hosted git repository.
nchammas pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git
The following commit(s) were added to refs/heads/master by this push:
new 700ef4623084 [SPARK-52598][DOC] Reorganize the Spark Connect docs into
a guide with a sidebar
700ef4623084 is described below
commit 700ef46230847acff3cfd279eebc03fc1dc660db
Author: lnc <[email protected]>
AuthorDate: Tue Nov 10 11:34:08 2026 -0500
[SPARK-52598][DOC] Reorganize the Spark Connect docs into a guide with a
sidebar
### What changes were proposed in this pull request?
This is nchammas's reorg from #51305 (which no longer rebases), brought
forward onto current master. The programming guide that was also in this PR
moves to a separate PR on top of this one, #59888.
The first three items are #51305's structure, and
`spark-connect-server-libs.md` is #51305's version of the page. The setup page
is rebuilt from current master's overview, split the way #51305 split it;
master's overview has grown since, so there is more of it.
- Spark Connect gets an entry in the Programming Guides dropdown and a left
sidebar like the SQL and Structured Streaming guides
(`_data/menu-spark-connect.yaml`,
`_includes/nav-left-wrapper-spark-connect.html`, `_layouts/global.html`).
- `spark-connect-overview.md` is split. The overview keeps the concepts
(what it is, how it works, how a client app differs from classic, what is
supported). The operational parts move to a new `spark-connect-setup.md`:
starting a server, the shells, connection strings, the persistent local server,
standalone apps, `spark.api.mode`, auth, reverse proxies.
- `app-dev-spark-connect.md` becomes `spark-connect-server-libs.md` (with
`redirect_from`), since server libraries are what that page is actually about.
The overview text it duplicated is dropped.
- Added on top of #51305, to the setup page: `start-connect-server.sh
--wait`, binding address and port, the port 15002 collision with
`remote("local[*]")`, the Python client's `/` restriction in connection string
parameter values (and its `%2F` escape), the `localhost` exception to a token
turning on TLS, a Python tab for the programmatic connection string.
- Also added on top of #51305, overview fixes: list the Go, Rust and Swift
clients under "What is supported", fix the `DataStreamWriter.htmll` link, drop
the "introduced in 3.4" wording here and in `index.md`.
### Why are the changes needed?
The Connect pages were only reachable from `index.md`,
`spark-standalone.md` and each other, and the overview had turned into a mix of
concepts and setup instructions.
### Does this PR introduce _any_ user-facing change?
Docs only. `app-dev-spark-connect.html` redirects to
`spark-connect-server-libs.html`.
### How was this patch tested?
Built the docs with `SKIP_API=1 SKIP_SCALADOC=1 SKIP_PYTHONDOC=1
SKIP_RDOC=1 SKIP_SQLDOC=1 SKIP_ERRORDOC=1 bundle exec jekyll build` and checked
the dropdown, sidebar, anchors and the redirect in `_site/`.
The setup page's examples were run against a 4.3.0 RC2 Connect server:
Python with the RC2 `pyspark` and `pyspark-client` packages, Scala through
`spark-shell --remote`. The connection string rules were checked in both
clients: the `/` restriction and `%2F` escape in the Python client's parser,
and the token and TLS behaviour for `localhost` in the Python and Scala channel
builders.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Code. The examples were run against real servers as
described above.
Closes #59613 from lisancao/SPARK-52598-connect-programming-guide.
Authored-by: lnc <[email protected]>
Signed-off-by: Nicholas Chammas <[email protected]>
skip-checks: true
---
docs/_data/menu-spark-connect.yaml | 23 +
docs/_includes/nav-left-wrapper-spark-connect.html | 6 +
docs/_layouts/global.html | 7 +-
docs/img/extending-spark-connect.png | Bin 118823 -> 0 bytes
docs/index.md | 15 +-
docs/spark-connect-overview.md | 512 +++------------------
...ark-connect.md => spark-connect-server-libs.md} | 142 ++----
...-connect-overview.md => spark-connect-setup.md} | 356 +++++++-------
8 files changed, 300 insertions(+), 761 deletions(-)
diff --git a/docs/_data/menu-spark-connect.yaml
b/docs/_data/menu-spark-connect.yaml
new file mode 100644
index 000000000000..7898a728c29d
--- /dev/null
+++ b/docs/_data/menu-spark-connect.yaml
@@ -0,0 +1,23 @@
+- text: Setting up Spark Connect
+ url: spark-connect-setup.html
+ subitems:
+ - text: Starting a Spark Connect server
+ url: spark-connect-setup.html#starting-a-spark-connect-server
+ - text: Interactive analysis
+ url: spark-connect-setup.html#interactive-analysis-with-spark-connect
+ - text: Connection strings
+ url: spark-connect-setup.html#connection-strings
+ - text: Persistent local server
+ url:
spark-connect-setup.html#faster-local-iteration-with-a-persistent-connect-server
+ - text: Standalone applications
+ url: spark-connect-setup.html#spark-connect-in-standalone-applications
+ - text: Switching between Spark Connect and Spark Classic
+ url:
spark-connect-setup.html#switching-between-spark-connect-and-spark-classic
+ - text: Client application authentication
+ url: spark-connect-setup.html#client-application-authentication
+ - text: Routing through a shared ingress
+ url:
spark-connect-setup.html#routing-through-a-shared-ingress-or-reverse-proxy
+- text: "Eager vs Lazy: Spark Connect vs Spark Classic"
+ url: spark-connect-gotchas.html
+- text: Extending Spark with Spark Server Libraries
+ url: spark-connect-server-libs.html
diff --git a/docs/_includes/nav-left-wrapper-spark-connect.html
b/docs/_includes/nav-left-wrapper-spark-connect.html
new file mode 100644
index 000000000000..bea84110da4c
--- /dev/null
+++ b/docs/_includes/nav-left-wrapper-spark-connect.html
@@ -0,0 +1,6 @@
+<div class="left-menu-wrapper">
+ <div class="left-menu">
+ <h3><a href="spark-connect-overview.html">Spark Connect Guide</a></h3>
+ {% include nav-left.html nav=include.nav-spark-connect %}
+ </div>
+</div>
diff --git a/docs/_layouts/global.html b/docs/_layouts/global.html
index ed156b7afd17..9dd0925f2c43 100755
--- a/docs/_layouts/global.html
+++ b/docs/_layouts/global.html
@@ -75,6 +75,7 @@
<a class="dropdown-item" href="{{ rel_path_to_root
}}rdd-programming-guide.html">RDDs, Accumulators, Broadcasts Vars</a>
<a class="dropdown-item" href="{{ rel_path_to_root
}}sql-programming-guide.html">SQL, DataFrames, and Datasets</a>
<a class="dropdown-item" href="{{ rel_path_to_root
}}streaming/index.html">Structured Streaming</a>
+ <a class="dropdown-item" href="{{ rel_path_to_root
}}spark-connect-overview.html">Spark Connect</a>
<a class="dropdown-item" href="{{ rel_path_to_root
}}streaming-programming-guide.html">Spark Streaming (DStreams)</a>
<a class="dropdown-item" href="{{ rel_path_to_root
}}ml-guide.html">MLlib (Machine Learning)</a>
<a class="dropdown-item" href="{{ rel_path_to_root
}}graphx-programming-guide.html">GraphX (Graph Processing)</a>
@@ -156,15 +157,17 @@
{% endif %}
<div class="container">
- {% if page.url contains "/ml" or page.url contains "/sql" or
page.url contains "/streaming/" or page.url contains "migration-guide.html" %}
+ {% if page.url contains "/ml" or page.url contains "/sql" or
page.url contains "/streaming/" or page.url contains "migration-guide.html" or
page.url contains "/spark-connect" %}
{% if page.url contains "migration-guide.html" %}
{% include nav-left-wrapper-migration.html
nav-migration=site.data.menu-migration %}
{% elsif page.url contains "/ml" %}
{% include nav-left-wrapper-ml.html
nav-mllib=site.data.menu-mllib nav-ml=site.data.menu-ml %}
{% elsif page.url contains "/streaming/" %}
{% include nav-left-wrapper-streaming.html
nav-streaming=site.data.menu-streaming %}
- {% else %}
+ {% elsif page.url contains "/sql" %}
{% include nav-left-wrapper-sql.html
nav-sql=site.data.menu-sql %}
+ {% elsif page.url contains "/spark-connect" %}
+ {% include nav-left-wrapper-spark-connect.html
nav-spark-connect=site.data.menu-spark-connect %}
{% endif %}
<input id="nav-trigger" class="nav-trigger" checked
type="checkbox">
<label for="nav-trigger"></label>
diff --git a/docs/img/extending-spark-connect.png
b/docs/img/extending-spark-connect.png
deleted file mode 100644
index 381d99bdda86..000000000000
Binary files a/docs/img/extending-spark-connect.png and /dev/null differ
diff --git a/docs/index.md b/docs/index.md
index 6c8acb7655e5..429d5378f979 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -81,13 +81,14 @@ Example applications are also provided in R. For example:
## Running Spark Client Applications Anywhere with Spark Connect
-Spark Connect is a new client-server architecture introduced in Spark 3.4 that
decouples Spark
-client applications and allows remote connectivity to Spark clusters. The
separation between
-client and server allows Spark and its open ecosystem to be leveraged from
anywhere, embedded
-in any application. In Spark 3.4, Spark Connect provides DataFrame API
coverage for PySpark and
-DataFrame/Dataset API support in Scala.
-
-To learn more about Spark Connect and how to use it, see [Spark Connect
Overview](spark-connect-overview.html).
+Spark Connect is a client-server architecture that decouples Spark client
applications from the
+Spark driver and allows remote connectivity to Spark clusters. The separation
between client
+and server allows Spark and its open ecosystem to be leveraged from anywhere,
embedded in any
+application. Spark Connect covers the DataFrame API in PySpark and the
DataFrame/Dataset API
+in Scala, and clients for other languages are developed in separate Apache
repositories.
+
+To learn more about Spark Connect, see [Spark Connect
Overview](spark-connect-overview.html);
+to run a server and connect to it, see [Setting up Spark
Connect](spark-connect-setup.html).
# Launching on a Cluster
diff --git a/docs/spark-connect-overview.md b/docs/spark-connect-overview.md
index 67f8766f59ce..9486feed85ad 100644
--- a/docs/spark-connect-overview.md
+++ b/docs/spark-connect-overview.md
@@ -17,22 +17,23 @@ license: |
See the License for the specific language governing permissions and
limitations under the License.
---
-**Building client-side Spark applications**
-In Apache Spark 3.4, Spark Connect introduced a decoupled client-server
-architecture that allows remote connectivity to Spark clusters using the
-DataFrame API and unresolved logical plans as the protocol. The separation
-between client and server allows Spark and its open ecosystem to be
-leveraged from everywhere. It can be embedded in modern data applications,
-in IDEs, Notebooks and programming languages.
+Spark Connect is a decoupled client-server architecture for Apache Spark. A
thin client
+library speaks to a Spark cluster over gRPC using the DataFrame API and
unresolved logical
+plans as the protocol, so Spark and its open ecosystem can be used from
anywhere:
+embedded in modern data applications, in IDEs, in notebooks and in programming
languages.
+Spark Connect has been part of Apache Spark since the 3.4 release.
-To get started, see [Quickstart: Spark
Connect](api/python/getting_started/quickstart_connect.html).
+To get started, see [Setting up Spark Connect](spark-connect-setup.html).
+
+* This will become a table of contents (this text will be scraped).
+{:toc}
<p style="text-align: center;">
<img src="img/spark-connect-api.png" title="Spark Connect API" alt="Spark
Connect API Diagram" />
</p>
-# How Spark Connect works
+## How Spark Connect works
The Spark Connect client library is designed to simplify Spark application
development. It is a thin API that can be embedded everywhere: in application
@@ -56,7 +57,7 @@ client through gRPC as Apache Arrow-encoded row batches.
<img src="img/spark-connect-communication.png" title="Spark Connect
communication" alt="Spark Connect communication" />
</p>
-## How Spark Connect client applications differ from classic Spark applications
+### How Spark Connect client applications differ from classic Spark
applications
One of the main design goals of Spark Connect is to enable a full separation
and
isolation of the client from the server. As a consequence, there are some
changes
@@ -67,390 +68,53 @@ that developers need to be aware of when using Spark
Connect:
the execution environment. In particular, in PySpark, the client does not
use Py4J
and thus the accessing the private fields holding the JVM implementation of
`DataFrame`,
`Column`, `SparkSession`, etc. is not possible (e.g. `df._jdf`).
-2. By design, the Spark Connect protocol uses Sparks logical
+2. By design, the Spark Connect protocol uses Spark's logical
plans as the abstraction to be able to declaratively describe the
operations to be executed
on the server. Consequently, the Spark Connect protocol does not support
all the
- execution APIs of Spark, most importantly RDDs.
+ execution APIs of Spark, most importantly RDDs. Alternatives for missing
RDD functionality
+ are provided as part of the higher-level DataFrame API.
3. Spark Connect provides a session-based client for its consumers. This means
that the
client does not have access to properties of the cluster that manipulate the
- environment for all connected clients. Most importantly, the client does
not have access
- to the static Spark configuration or the SparkContext.
+ environment for all connected clients. Most importantly, the client cannot
change the
+ static Spark configuration and has no access to the SparkContext.
+
+Apart from these differences the Spark Connect API is code-compatible with
classic Spark
+applications: the DataFrame code they contain does not change. What changes is
around that code:
+how the application is launched and configured, where its dependencies go, and
when a plan is
+analyzed. [Setting up Spark Connect](spark-connect-setup.html) covers starting
a server,
+connecting to it and switching an application between the two modes; the
+[Eager vs Lazy](spark-connect-gotchas.html) page covers the behavioral
differences, starting with
+the deferred analysis of query plans.
-# Operational benefits of Spark Connect
+## Operational benefits of Spark Connect
With this new architecture, Spark Connect mitigates several multi-tenant
operational issues:
**Stability**: Applications that use too much memory will now only impact their
-own environment as they can run in their own processes. Users can define their
-own dependencies on the client and don't need to worry about potential
conflicts
-with the Spark driver.
+own environment as they can run in their own processes. Dependencies installed
on
+the client do not conflict with the Spark driver's, although anything a UDF
imports
+still has to be available on the server.
**Upgradability**: The Spark driver can now seamlessly be upgraded
independently
of applications, for example to benefit from performance improvements and
security fixes.
This means applications can be forward-compatible, as long as the server-side
RPC
definitions are designed to be backwards compatible.
+**Remote connectivity**: The decoupled architecture allows remote connectivity
to Spark beyond SQL
+and JDBC: any application can now interactively use Spark "as a service".
+
+**Simplicity**: The Spark Connect API is the DataFrame API and SQL, without
the lower-level RDD
+API (see [How Spark Connect client applications differ from classic Spark
applications](#how-spark-connect-client-applications-differ-from-classic-spark-applications)).
+It is fully declarative and consequently easy to learn for new users familiar
with SQL.
+
**Debuggability and observability**: Spark Connect enables interactive
debugging
during development directly from your favorite IDE. Similarly, applications can
be monitored using the application's framework native metrics and logging
libraries.
-# How to use Spark Connect
-
-Spark Connect is available and supports PySpark and Scala
-applications. We will walk through how to run an Apache Spark server with Spark
-Connect and connect to it from a client application using the Spark Connect
client
-library.
-
-## Download and start Spark server with Spark Connect
-
-First, download Spark from the
-[Download Apache Spark](https://spark.apache.org/downloads.html) page. Choose
the
-latest release in the release drop down at the top of the page. Then choose
your package type, typically
-“Pre-built for Apache Hadoop 3.5 and later”, and click the link to download.
-
-Now extract the Spark package you just downloaded on your computer, for
example:
-
-```bash
-tar -xvf spark-{{site.SPARK_VERSION_SHORT}}-bin-hadoop3.tgz
-```
-
-In a terminal window, go to the `spark` folder in the location where you
extracted
-Spark before and run the `start-connect-server.sh` script to start Spark
server with
-Spark Connect, like in this example:
-
-```bash
-./sbin/start-connect-server.sh
-```
-
-Alternatively, `./bin/spark-connect-shell` starts an interactive Scala shell
with the Connect server hosted inside the shell process itself.
-
-Make sure to use the same version of the package as the Spark version you
-downloaded previously. In this example, Spark {{site.SPARK_VERSION_SHORT}}
with Scala 2.13.
-
-Now Spark server is running and ready to accept Spark Connect sessions from
client
-applications. In the next section we will walk through how to use Spark Connect
-when writing client applications.
-
-## Use Spark Connect for interactive analysis
-<div class="codetabs">
-
-<div data-lang="python" markdown="1">
-When creating a Spark session, you can specify that you want to use Spark
Connect
-and there are a few ways to do that outlined as follows.
-
-If you do not use one of the mechanisms outlined here, your Spark session will
-work just like before, without leveraging Spark Connect.
-
-### Set SPARK_REMOTE environment variable
-
-If you set the `SPARK_REMOTE` environment variable on the client machine where
your
-Spark client application is running and create a new Spark Session as in the
following
-example, the session will be a Spark Connect session. With this approach,
there is no
-code change needed to start using Spark Connect.
-
-In a terminal window, set the `SPARK_REMOTE` environment variable to point to
the
-local Spark server you started previously on your computer:
-
-{% highlight bash %}
-export SPARK_REMOTE="sc://localhost"
-{% endhighlight %}
-
-And start the Spark shell as usual:
-
-{% highlight bash %}
-./bin/pyspark
-{% endhighlight %}
-
-The PySpark shell is now connected to Spark using Spark Connect as indicated
in the welcome message:
-
-{% highlight python %}
-Client connected to the Spark Connect server at localhost
-{% endhighlight %}
-
-### Specify Spark Connect when creating Spark session
-
-You can also specify that you want to use Spark Connect explicitly when you
-create a Spark session.
-
-For example, you can launch the PySpark shell with Spark Connect as
-illustrated here.
-
-To launch the PySpark shell with Spark Connect, simply include the `remote`
-parameter and specify the location of your Spark server. We are using
`localhost`
-in this example to connect to the local Spark server we started previously:
-
-{% highlight bash %}
-./bin/pyspark --remote "sc://localhost"
-{% endhighlight %}
-
-And you will notice that the PySpark shell welcome message tells you that
-you have connected to Spark using Spark Connect:
-
-{% highlight python %}
-Client connected to the Spark Connect server at localhost
-{% endhighlight %}
-
-You can also check the Spark session type. If it includes `.connect.` you
-are using Spark Connect as shown in this example:
-
-{% highlight python %}
-SparkSession available as 'spark'.
->>> type(spark)
-<class 'pyspark.sql.connect.session.SparkSession'>
-{% endhighlight %}
-
-Now you can run PySpark code in the shell to see Spark Connect in action:
-
-{% highlight python %}
->>> columns = ["id", "name"]
->>> data = [(1,"Sarah"), (2,"Maria")]
->>> df = spark.createDataFrame(data).toDF(*columns)
->>> df.show()
-+---+-----+
-| id| name|
-+---+-----+
-| 1|Sarah|
-| 2|Maria|
-+---+-----+
-{% endhighlight %}
-
-</div>
-
-<div data-lang="scala" markdown="1">
-For the Scala shell, we use an Ammonite-based REPL. Otherwise, very similar
with PySpark shell.
-
-{% highlight bash %}
-./bin/spark-shell --remote "sc://localhost"
-{% endhighlight %}
-
-A greeting message will appear when the REPL successfully initializes:
-{% highlight bash %}
-Welcome to
- ____ __
- / __/__ ___ _____/ /__
- _\ \/ _ \/ _ `/ __/ '_/
- /___/ .__/\_,_/_/ /_/\_\ version {{site.SPARK_VERSION}}
- /_/
-
-Type in expressions to have them evaluated.
-Spark session available as 'spark'.
-{% endhighlight %}
-
-By default, the REPL will attempt to connect to a local Spark Server.
-Run the following Scala code in the shell to see Spark Connect in action:
-
-{% highlight scala %}
-@ spark.range(10).count
-res0: Long = 10L
-{% endhighlight %}
-
-### Configure client-server connection
-
-By default, the REPL will attempt to connect to a local Spark Server on port
15002.
-The connection, however, may be configured in several ways as described in
this configuration
-[reference](https://github.com/apache/spark/blob/master/sql/connect/docs/client-connection-string.md).
-
-#### Set SPARK_REMOTE environment variable
-
-The SPARK_REMOTE environment variable can be set on the client machine to
customize the client-server
-connection that is initialized at REPL startup.
-
-{% highlight bash %}
-export SPARK_REMOTE="sc://myhost.com:443/;token=ABCDEFG"
-./bin/spark-shell
-{% endhighlight %}
-
-or
-
-{% highlight bash %}
-SPARK_REMOTE="sc://myhost.com:443/;token=ABCDEFG" spark-connect-repl
-{% endhighlight %}
-
-#### Configure programmatically with a connection string
-
-The connection may also be programmatically created using
_SparkSession#builder_ as in this example:
-
-{% highlight scala %}
-@ import org.apache.spark.sql.SparkSession
-@ val spark =
SparkSession.builder.remote("sc://localhost:443/;token=ABCDEFG").getOrCreate()
-{% endhighlight %}
-
-</div>
-</div>
-
-## Faster local iteration with a persistent Connect server
+## What is supported
-When you develop or test locally with
-
-```python
-from pyspark.sql import SparkSession
-spark = SparkSession.builder.remote("local[*]").getOrCreate()
-```
-
-PySpark boots a fresh in-process Spark Connect server that lives only as long
as that Python
-process. Every `python script.py` invocation (or every new test worker
process) therefore re-pays
-the one-time startup cost -- JVM warmup, `SparkContext` construction, and
Connect server boot --
-which can take a few seconds and makes a quick edit/run loop feel slow.
-
-To amortize that cost across runs, start one persistent local Spark Connect
server and point
-every run at it:
-
-```bash
-# Start once; it stays up across runs. (--master is optional; it defaults to
local[*].)
-$SPARK_HOME/sbin/start-connect-server.sh --master "local[*]"
-
-# Every run reconnects instead of booting a new server.
-python -c 'from pyspark.sql import SparkSession;
SparkSession.builder.remote("sc://localhost:15002").getOrCreate()'
-
-# Stop it when you are done.
-$SPARK_HOME/sbin/stop-connect-server.sh
-```
-
-Alternatively, on POSIX systems PySpark can manage this persistent server for
you. With
-`SPARK_LOCAL_CONNECT_REUSE=1` set (or `spark.local.connect.reuse=true` on the
builder),
-`SparkSession.builder.remote("local[*]").getOrCreate()` starts a persistent
server through
-`sbin/start-connect-server.sh` on the first run and reconnects to it on later
runs, so scripts
-keep the plain `local[*]` URL:
-
-```bash
-export SPARK_LOCAL_CONNECT_REUSE=1
-
-# The first run starts the server; later runs reconnect to it.
-python -c 'from pyspark.sql import SparkSession;
SparkSession.builder.remote("local[*]").getOrCreate()'
-
-# Stop the managed server when you are done.
-python -m pyspark.sql.connect.local_server --stop
-```
-
-The managed server is an ordinary `spark-daemon.sh` daemon, but it runs with a
per-user pid
-directory and ident string so it cannot collide with a server you started by
hand -- which also
-means a plain `sbin/stop-connect-server.sh` does not find it. The `--stop`
command signals the
-recorded server and cleans up the discovery file; killing the server's pid
directly also works,
-and the next run notices the dead server and starts a fresh one.
-
-This managed-server workflow is experimental. The `--stop` command and the
discovery file
-location and format may change in a future release, for example if local
server management is
-folded into a unified `spark connect` CLI.
-
-The connection details (host, port, auth token, pid, Spark version) are
recorded in a discovery
-file in a private per-user directory; set `SPARK_LOCAL_CONNECT_DISCOVERY` to
override its
-location. A run reconnects only to a server whose Spark version matches. After
upgrading Spark,
-the server from the previous version cannot be reused and the next run fails
with an error asking
-you to stop it; run the `--stop` command above and rerun to start a fresh
server.
-
-Each run connects as its own Connect session, so session-local state -- temp
views, runtime SQL
-configurations, and session artifacts -- is fresh on every run and never leaks
between runs. State
-backed by the shared `SparkContext` (the persistent catalog/warehouse, global
temp views, and
-cached datasets) *is* shared across runs, so namespace per-run databases or
clear that state
-yourself if your runs must be fully isolated.
-
-## Use Spark Connect in standalone applications
-
-<div class="codetabs">
-
-
-<div data-lang="python" markdown="1">
-
-First, install PySpark with `pip install
pyspark-client=={{site.SPARK_VERSION_SHORT}}` or if building a packaged PySpark
application/library,
-add it your setup.py file as:
-{% highlight python %}
-install_requires=[
-'pyspark-client=={{site.SPARK_VERSION_SHORT}}'
-]
-{% endhighlight %}
-
-When writing your own code, include the `remote` function with a reference to
-your Spark server when you create a Spark session, as in this example:
-
-{% highlight python %}
-from pyspark.sql import SparkSession
-spark = SparkSession.builder.remote("sc://localhost").getOrCreate()
-{% endhighlight %}
-
-
-For illustration purposes, we’ll create a simple Spark Connect application,
SimpleApp.py:
-{% highlight python %}
-"""SimpleApp.py"""
-from pyspark.sql import SparkSession
-
-logFile = "YOUR_SPARK_HOME/README.md" # Should be some file on your system
-spark =
SparkSession.builder.remote("sc://localhost").appName("SimpleApp").getOrCreate()
-logData = spark.read.text(logFile).cache()
-
-numAs = logData.filter(logData.value.contains('a')).count()
-numBs = logData.filter(logData.value.contains('b')).count()
-
-print("Lines with a: %i, lines with b: %i" % (numAs, numBs))
-
-spark.stop()
-{% endhighlight %}
-
-This program just counts the number of lines containing ‘a’ and the number
containing ‘b’ in a text file.
-Note that you’ll need to replace YOUR_SPARK_HOME with the location where Spark
is installed.
-
-We can run this application with the regular Python interpreter as follows:
-{% highlight python %}
-# Use the Python interpreter to run your application
-$ python SimpleApp.py
-...
-Lines with a: 72, lines with b: 39
-{% endhighlight %}
-</div>
-
-
-<div data-lang="scala" markdown="1">
-To use Spark Connect as part of a Scala application/project, we first need to
include the right dependencies.
-Using the `sbt` build system as an example, we add the following dependencies
to the `build.sbt` file:
-{% highlight sbt %}
-libraryDependencies += "org.apache.spark" %% "spark-connect-client-jvm" %
"{{site.SPARK_VERSION_SHORT}}"
-{% endhighlight %}
-
-When writing your own code, include the `remote` function with a reference to
-your Spark server when you create a Spark session, as in this example:
-
-{% highlight scala %}
-import org.apache.spark.sql.SparkSession
-val spark = SparkSession.builder().remote("sc://localhost").getOrCreate()
-{% endhighlight %}
-
-
-**Note**: Operations that reference User Defined Code such as UDFs, filter,
map, etc require a
-[ClassFinder](https://github.com/apache/spark/blob/master/sql/connect/common/src/main/scala/org/apache/spark/sql/connect/client/ClassFinder.scala)
-to be registered to pickup and upload any required classfiles. Also, any JAR
dependencies must be uploaded to the server using `SparkSession#AddArtifact`.
-
-Example:
-{% highlight scala %}
-import org.apache.spark.sql.connect.client.REPLClassDirMonitor
-// Register a ClassFinder to monitor and upload the classfiles from the build
output.
-val classFinder = new REPLClassDirMonitor(<ABSOLUTE_PATH_TO_BUILD_OUTPUT_DIR>)
-spark.registerClassFinder(classFinder)
-
-// Upload JAR dependencies
-spark.addArtifact(<ABSOLUTE_PATH_JAR_DEP>)
-{% endhighlight %}
-Here, `ABSOLUTE_PATH_TO_BUILD_OUTPUT_DIR` is the output directory where the
build system writes classfiles into
-and `ABSOLUTE_PATH_JAR_DEP` is the location of the JAR on the local file
system.
-
-The `REPLClassDirMonitor` is a provided implementation of `ClassFinder` that
monitors a specific directory but
-one may implement their own class extending `ClassFinder` for customized
search and monitoring.
-
-</div>
-</div>
-
-For more information on application development with Spark Connect as well as
extending Spark Connect
-with custom functionality, see [Application Development with Spark
Connect](app-dev-spark-connect.html).
-# Client application authentication
-
-While Spark Connect does not have built-in authentication, it is designed to
-work seamlessly with your existing authentication infrastructure. Its gRPC
-HTTP/2 interface allows for the use of authenticating proxies, which makes
-it possible to secure Spark Connect without having to implement authentication
-logic in Spark directly.
-
-# What is supported
-
-**PySpark**: Since Spark 3.4, Spark Connect supports most PySpark APIs,
including
+**PySpark**: Spark Connect supports most PySpark APIs, including
[DataFrame](api/python/reference/pyspark.sql/dataframe.html),
[Functions](api/python/reference/pyspark.sql/functions.html), and
[Column](api/python/reference/pyspark.sql/column.html). However,
@@ -461,7 +125,7 @@ supported in the [API
reference](api/python/reference/index.html) documentation.
Supported APIs are labeled "Supports Spark Connect" so you can check whether
the
APIs you are using are available before migrating existing code to Spark
Connect.
-**Scala**: Since Spark 3.5, Spark Connect supports most Scala APIs, including
+**Scala**: Spark Connect supports most Scala APIs, including
[Dataset](api/scala/org/apache/spark/sql/Dataset.html),
[functions](api/scala/org/apache/spark/sql/functions$.html),
[Column](api/scala/org/apache/spark/sql/Column.html),
@@ -473,89 +137,29 @@ additional set-up requirements.
Majority of the Streaming API is supported, including
[DataStreamReader](api/scala/org/apache/spark/sql/streaming/DataStreamReader.html),
-[DataStreamWriter](api/scala/org/apache/spark/sql/streaming/DataStreamWriter.htmll),
+[DataStreamWriter](api/scala/org/apache/spark/sql/streaming/DataStreamWriter.html),
[StreamingQuery](api/scala/org/apache/spark/sql/streaming/StreamingQuery.html)
and
[StreamingQueryListener](api/scala/org/apache/spark/sql/streaming/StreamingQueryListener.html).
APIs such as [SparkContext](api/scala/org/apache/spark/SparkContext.html)
and [RDD](api/scala/org/apache/spark/rdd/RDD.html) are unsupported in Spark
Connect.
-Support for more APIs is planned for upcoming Spark releases.
-
-# Routing through a shared ingress or reverse proxy
-
-When several services share a single hostname behind a Kubernetes Ingress (or
another
-reverse proxy), it is tempting to give each service a URL path prefix (for
example
-`sc://host/sparkConnect`) and route on that path. This does not work for gRPC:
the
-gRPC method name *is* the HTTP/2 `:path`
(`/spark.connect.SparkConnectService/ExecutePlan`),
-so a connection string cannot carry a separate routing path. Prepending a
prefix to the
-`:path` produces an unknown method and the server responds with
`UNIMPLEMENTED`, unless the
-proxy is configured to strip the prefix back off before forwarding, a
two-sided contract
-that is not part of gRPC's design.
-
-The routing dimension that *is* free is the HTTP/2 `:authority` (the virtual
host). Set it
-to a routing tag with the `grpc.default_authority` channel option, and route
on it at the
-proxy (for example, an Ingress `host:` rule). The client still dials the
shared hostname
-(`default_authority` only overrides the `:authority` header used for routing,
not the address
-it connects to), and the gRPC method `:path` is never touched, so no path
rewrite is needed.
-This is the approach the gRPC maintainers recommend for this scenario
-([grpc/grpc#14900](https://github.com/grpc/grpc/issues/14900)).
-
-The example below uses the Python client, which exposes gRPC channel options
directly:
-
-{% highlight python %}
-from pyspark.sql.connect.session import SparkSession
-from pyspark.sql.connect.client import DefaultChannelBuilder
-
-cb = DefaultChannelBuilder("sc://myhost.com:443")
-cb.setChannelOption("grpc.default_authority", "sparkconnect") # routing tag
-spark = SparkSession.builder.channelBuilder(cb).getOrCreate()
-{% endhighlight %}
-
-A corresponding Kubernetes Ingress routes on that tag and keeps the service at
path `/`
-(no subpath, no rewrite). Note the routing tag must be a lowercase
-[RFC 1123](https://datatracker.ietf.org/doc/html/rfc1123) name, since a
Kubernetes Ingress
-`host:` requires one:
-
-{% highlight yaml %}
-spec:
- rules:
- - host: sparkconnect # matches grpc.default_authority
- http:
- paths:
- - path: /
- pathType: Prefix
- backend:
- service:
- name: spark-connect-server
- port: { number: 15002 }
-{% endhighlight %}
-
-**Over TLS**, gRPC uses the `:authority` as the certificate-verification name
by default,
-so overriding it with a routing tag would fail verification (the tag is not in
the server
-certificate's SAN). Keep the two names separate: set
`grpc.ssl_target_name_override` to the
-real server hostname (used for certificate verification and SNI) and
`grpc.default_authority`
-to the routing tag.
-
-{% highlight python %}
-cb = DefaultChannelBuilder("sc://myhost.com:443/;use_ssl=true")
-cb.setChannelOption("grpc.ssl_target_name_override", "myhost.com") #
certificate verification / SNI
-cb.setChannelOption("grpc.default_authority", "sparkconnect") # routing
tag
-spark = SparkSession.builder.channelBuilder(cb).getOrCreate()
-{% endhighlight %}
-
-`use_ssl=true` verifies the server certificate against the system's trusted CA
store. If your
-gateway's certificate is issued by a CA the client does not trust by default
(a self-signed or
-internal CA), make that CA trusted on the client side (for example, via
-`GRPC_DEFAULT_SSL_ROOTS_FILE_PATH`) rather than through the connection string.
Configuring the
-proxy's own TLS (which certificate it presents for which hostname) is part of
your ingress
-setup and is out of scope here.
-
-Two notes on `grpc.ssl_target_name_override`:
-gRPC documents it as testing-oriented because its typical misuse is to *mask*
a certificate
-name mismatch (verifying against a name the server does not actually present,
which defeats
-hostname verification). Here it is set to the real, verified hostname, so the
certificate is
-still checked correctly; it only prevents the routing tag from being used as
the verification
-name. If you prefer to avoid the option entirely, issue the server certificate
with the routing
-tag included in its SAN; then `grpc.default_authority` alone is sufficient and
no override is
-needed.
+**Other clients**: Because the protocol is language-agnostic, Spark Connect
clients exist
+outside the Apache Spark repository as well. The Apache Software Foundation
hosts clients for
+[Go](https://github.com/apache/spark-connect-go),
+[Rust](https://github.com/apache/spark-connect-rust) and
+[Swift](https://github.com/apache/spark-connect-swift), each released on its
own schedule.
+
+## Where to go from here
+
+* [Setting up Spark Connect](spark-connect-setup.html): start a Spark Connect
server, connect
+ to it from the shells and from standalone applications, run a persistent
local server for
+ development, switch existing applications between Spark Classic and Spark
Connect, and put
+ the server behind an authenticating proxy.
+* [Eager vs Lazy: Spark Connect vs Spark Classic](spark-connect-gotchas.html):
how deferred
+ analysis changes the behavior of temporary views, UDFs and error reporting,
and how to write
+ code that works in both modes.
+* [Extending Spark with Spark Server
Libraries](spark-connect-server-libs.html): add custom
+ server-side logic and expose it to clients through the Spark Connect
protocol.
+* [Quickstart: Spark
Connect](api/python/getting_started/quickstart_connect.html): a notebook
+ walkthrough for PySpark.
diff --git a/docs/app-dev-spark-connect.md b/docs/spark-connect-server-libs.md
similarity index 56%
rename from docs/app-dev-spark-connect.md
rename to docs/spark-connect-server-libs.md
index e61aa05d3f11..555d2aed5602 100644
--- a/docs/app-dev-spark-connect.md
+++ b/docs/spark-connect-server-libs.md
@@ -1,6 +1,7 @@
---
layout: global
-title: Application Development with Spark Connect
+title: Extending Spark with Spark Server Libraries
+redirect_from: app-dev-spark-connect.html
license: |
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
@@ -17,18 +18,6 @@ license: |
See the License for the specific language governing permissions and
limitations under the License.
---
-**Spark Connect Overview**
-
-In Apache Spark 3.4, Spark Connect introduced a decoupled client-server
-architecture that allows remote connectivity to Spark clusters using the
-DataFrame API and unresolved logical plans as the protocol. The separation
-between client and server allows Spark and its open ecosystem to be
-leveraged from everywhere. It can be embedded in modern data applications,
-in IDEs, Notebooks and programming languages.
-
-To learn more about Spark Connect, see [Spark Connect
Overview](spark-connect-overview.html).
-
-# Redefining Spark Applications using Spark Connect
With its decoupled client-server architecture, Spark Connect simplifies how
Spark Applications are
developed.
@@ -46,73 +35,21 @@ it easy for both types of applications to evolve alongside
Spark. As illustrated
Client applications connect to Spark using the Spark Connect API, which is
essentially the
DataFrame API and fully declarative.
-<p style="text-align: center;">
- <img src="img/extending-spark-connect.png" title="Figure 1: Architecture"
alt="Extending Spark
-Connect Diagram"/>
-</p>
+<figure style="text-align: center;">
+ <img
+ src="img/extending-spark-connect-labelled.png"
+ alt="Extending Spark Connect Diagram"
+ />
+ <figcaption>Figure 1: Architecture</figcaption>
+</figure>
+
Spark Server Libraries extend Spark. They typically provide additional
server-side logic integrated
with Spark, which is exposed to client applications as part of the Spark
Connect API, using Spark
Connect extension points. For example, the _Spark Server Library_ consists of
custom
-service-side logic (as indicated by the blue box labeled _Custom Library
Plugin_), which is exposed
-to the client via the blue box as part of the Spark Connect API. The client
uses this API, e.g.,
-alongside PySpark or the Spark Scala client, making it easy for Spark client
applications to work
-with the custom logic/library.
-
-## Spark API Mode: Spark Client and Spark Classic
-
-Spark provides the API mode, `spark.api.mode` configuration, enabling Spark
Classic applications
-to seamlessly switch to Spark Connect. Depending on the value of
`spark.api.mode`, the application
-can run in either Spark Classic or Spark Connect mode. Here is an example:
-
-{% highlight python %}
-from pyspark.sql import SparkSession
-
-SparkSession.builder.config("spark.api.mode",
"connect").master("...").getOrCreate()
-{% endhighlight %}
-
-You can also apply this configuration to both Scala and PySpark applications
when submitting yours:
-
-{% highlight bash %}
-spark-submit --master "..." --conf spark.api.mode=connect
-{% endhighlight %}
-
-Additionally, Spark Connect offers convenient options for local testing. By
setting `spark.remote`
-to `local[...]` or `local-cluster[...]`, you can start a local Spark Connect
server and access a Spark
-Connect session.
-
-This is similar to using `--conf spark.api.mode=connect` with `--master ...`.
However, note that
-`spark.remote` and `--remote` are limited to `local*` values, while `--conf
spark.api.mode=connect`
-with `--master ...` supports additional cluster URLs, such as spark://, for
broader compatibility with
-Spark Classic.
-
-## Spark Client Applications
-
-Spark Client Applications are the _regular Spark applications_ that Spark
users develop today, e.g.,
-ETL pipelines, data preparation, or model training or inference. These are
typically built using
-Sparks declarative DataFrame and DataSet APIs. With Spark Connect, the core
behaviour remains the
-same, but there are a few differences:
-* Lower-level, non-declarative APIs (RDDs) can no longer be directly used from
Spark Client
-applications. Alternatives for missing RDD functionality are provided as part
of the higher-level
-DataFrame API.
-* Client applications no longer have direct access to the Spark driver JVM;
they are fully
-separated from the server.
-
-Client applications based on Spark Connect can be submitted in the same way as
any previous job.
-In addition, Spark Client Applications based on Spark Connect have several
benefits compared to
-classic Spark applications using earlier Spark versions (3.4 and below):
-* _Upgradability_: Upgrading to new Spark Server versions is seamless, as the
Spark Connect API
-abstracts any changes/improvements on the server side. Client- and server APIs
are cleanly
-separated.
-* _Simplicity_: The number of APIs exposed to the user is reduced from 3 to 2.
The Spark Connect API
-is fully declarative and consequently easy to learn for new users familiar
with SQL.
-* _Stability_: When using Spark Connect, the client applications no longer run
on the Spark driver
-and, therefore don’t cause and are not affected by any instability on the
server.
-* _Remote connectivity_: The decoupled architecture allows remote connectivity
to Spark beyond SQL
-and JDBC: any application can now interactively use Spark “as a service”.
-* _Backwards compatibility_: The Spark Connect API is code-compatible with
earlier Spark versions,
-except for the usage of RDDs, for which a list of alternative APIs is provided
in Spark Connect.
-
-## Spark Server Libraries
+server-side logic (the blue box labeled _Plugin_, with its _App Logic_), which
is exposed to
+the client via the blue _Proto API_ box as part of the Spark Connect API. The
client uses this
+API, e.g., alongside PySpark or the Spark Scala client, making it easy for
Spark client
+applications to work with the custom logic/library.
Until Spark 3.4, extensions to Spark (e.g., [Spark
ML](ml-guide#:~:text=What%20is%20%E2%80%9CSpark%20ML%E2%80%9D%3F,to%20emphasize%20the%20pipeline%20concept.)
or [Spark-NLP](https://github.com/JohnSnowLabs/spark-nlp)) were built and
deployed like Spark
@@ -122,31 +59,23 @@ exposed to a client, which differs from existing extension
points in Spark such
[SparkSession
extensions](api/java/org/apache/spark/sql/SparkSessionExtensions.html) or
[Spark Plugins](api/java/org/apache/spark/api/plugin/SparkPlugin.html).
-### Getting Started: Extending Spark with Spark Server Libraries
-
-Spark Connect is available and supports PySpark and Scala
-applications. We will walk through how to run an Apache Spark server with Spark
-Connect and connect to it from a client application using the Spark Connect
client
-library.
+* This will become a table of contents (this text will be scraped).
+{:toc}
-A Spark Server Library consists of the following components, illustrated in
Fig. 2:
+A Spark Server Library consists of the following components, numbered in Fig.
1:
1. The Spark Connect protocol extension (blue box _Proto_ API)
2. A Spark Connect Plugin.
3. The application logic that extends Spark.
4. The client package that exposes the Spark Server Library application logic
to the Spark Client
Application, alongside PySpark or the Scala Spark Client.
-<p style="text-align: center;">
- <img src="img/extending-spark-connect-labelled.png" title="Figure 2:
Labelled Architecture" alt="Extending Spark
-Connect Diagram - Labelled Steps"/>
-</p>
-#### (1) Spark Connect Protocol Extension
+## Spark Connect Protocol Extension
To extend Spark with a new Spark Server Library, developers can extend the
three main operation
types in the Spark Connect protocol: _Relation_, _Expression_, and _Command_.
-{% highlight protobuf %}
+```protobuf
message Relation {
oneof rel_type {
Read read = 1;
@@ -169,25 +98,26 @@ message Command {
// ...
google.protobuf.Any extension = 999;
}
-}
-{% endhighlight %}
+}
+```
Their extension fields allow serializing arbitrary protobuf messages as part
of the Spark Connect
protocol. These messages represent the parameters or state of the extension
implementation.
To build a custom expression type, the developer first defines the custom
protobuf definition
of the expression.
-{% highlight protobuf %}
+```protobuf
message ExamplePluginExpression {
Expression child = 1;
string custom_field = 2;
}
-{% endhighlight %}
+```
-#### (2) Spark Connect Plugin implementation with (3) custom application logic
+## Spark Connect Plugin implementation with custom application logic
-As a next step, the developer implements the _ExpressionPlugin_ class of Spark
Connect with custom
+As a next step, the developer implements the `ExpressionPlugin` class of Spark
Connect with custom
application logic based on the input parameters of the protobuf message.
-{% highlight protobuf %}
+
+```scala
class ExampleExpressionPlugin extends ExpressionPlugin {
override def transform(
relation: protobuf.Any,
@@ -202,22 +132,22 @@ class ExampleExpressionPlugin extends ExpressionPlugin {
exp.getChild), exp.getCustomField)(explicitMetadata = None))
}
}
-{% endhighlight %}
+```
Once the application logic is developed, the code must be packaged as a jar
and Spark must be
configured to pick up the additional logic. The relevant Spark configuration
options are:
-* _spark.jars_ which define the location of the Jar file containing the
application logic built for
+* `spark.jars` which define the location of the Jar file containing the
application logic built for
the custom expression.
-* _spark.connect.extensions.expression.classes_ specifying the full class name
+* `spark.connect.extensions.expression.classes` specifying the full class name
of each expression extension loaded by Spark. Based on these configuration
options, Spark will
load the values at startup and make them available for processing.
-#### (4) Spark Server Library Client Package
+## Spark Server Library Client Package
Once the server component is deployed, any client can use it with the right
protobuf messages.
In the example above, the following message payload sent to the Spark Connect
endpoint would be
enough to trigger the extension mechanism.
-{% highlight json %}
+```json
{
"project": {
"input": {
@@ -234,14 +164,14 @@ enough to trigger the extension mechanism.
}
]
}
-}
-{% endhighlight %}
+}
+```
To make the example available in Python, the application developer provides a
Python library that
wraps the new expression and embeds it into PySpark. The easiest way to
provide a function for any
expression is to take a PySpark column instance as an argument and return a
new Column instance
with the expression applied.
-{% highlight python %}
+```python
from pyspark.sql.connect.column import Expression
import pyspark.sql.connect.proto as proto
@@ -267,4 +197,4 @@ def example_expression(col: Column) -> Column:
# Using the expression in the Spark Connect client code.
df = spark.read.table("samples.nyctaxi.trips")
df.select(example_expression(df["fare_amount"])).collect()
-{% endhighlight %}
\ No newline at end of file
+```
diff --git a/docs/spark-connect-overview.md b/docs/spark-connect-setup.md
similarity index 62%
copy from docs/spark-connect-overview.md
copy to docs/spark-connect-setup.md
index 67f8766f59ce..01cff38b6cf9 100644
--- a/docs/spark-connect-overview.md
+++ b/docs/spark-connect-setup.md
@@ -1,6 +1,6 @@
---
layout: global
-title: Spark Connect Overview
+title: Setting up Spark Connect
license: |
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
@@ -17,92 +17,15 @@ license: |
See the License for the specific language governing permissions and
limitations under the License.
---
-**Building client-side Spark applications**
-
-In Apache Spark 3.4, Spark Connect introduced a decoupled client-server
-architecture that allows remote connectivity to Spark clusters using the
-DataFrame API and unresolved logical plans as the protocol. The separation
-between client and server allows Spark and its open ecosystem to be
-leveraged from everywhere. It can be embedded in modern data applications,
-in IDEs, Notebooks and programming languages.
-
-To get started, see [Quickstart: Spark
Connect](api/python/getting_started/quickstart_connect.html).
-
-<p style="text-align: center;">
- <img src="img/spark-connect-api.png" title="Spark Connect API" alt="Spark
Connect API Diagram" />
-</p>
-
-# How Spark Connect works
-
-The Spark Connect client library is designed to simplify Spark application
-development. It is a thin API that can be embedded everywhere: in application
-servers, IDEs, notebooks, and programming languages. The Spark Connect API
-builds on Spark's DataFrame API using unresolved logical plans as a
-language-agnostic protocol between the client and the Spark driver.
-
-The Spark Connect client translates DataFrame operations into unresolved
-logical query plans which are encoded using protocol buffers. These are sent
-to the server using the gRPC framework.
-
-The Spark Connect endpoint embedded on the Spark Server receives and
-translates unresolved logical plans into Spark's logical plan operators.
-This is similar to parsing a SQL query, where attributes and relations are
-parsed and an initial parse plan is built. From there, the standard Spark
-execution process kicks in, ensuring that Spark Connect leverages all of
-Spark's optimizations and enhancements. Results are streamed back to the
-client through gRPC as Apache Arrow-encoded row batches.
-
-<p style="text-align: center;">
- <img src="img/spark-connect-communication.png" title="Spark Connect
communication" alt="Spark Connect communication" />
-</p>
-
-## How Spark Connect client applications differ from classic Spark applications
-
-One of the main design goals of Spark Connect is to enable a full separation
and
-isolation of the client from the server. As a consequence, there are some
changes
-that developers need to be aware of when using Spark Connect:
-
-1. The client does not run in the same process as the Spark driver. This means
that
- the client cannot directly access and interact with the driver JVM to
manipulate
- the execution environment. In particular, in PySpark, the client does not
use Py4J
- and thus the accessing the private fields holding the JVM implementation of
`DataFrame`,
- `Column`, `SparkSession`, etc. is not possible (e.g. `df._jdf`).
-2. By design, the Spark Connect protocol uses Sparks logical
- plans as the abstraction to be able to declaratively describe the
operations to be executed
- on the server. Consequently, the Spark Connect protocol does not support
all the
- execution APIs of Spark, most importantly RDDs.
-3. Spark Connect provides a session-based client for its consumers. This means
that the
- client does not have access to properties of the cluster that manipulate the
- environment for all connected clients. Most importantly, the client does
not have access
- to the static Spark configuration or the SparkContext.
-
-# Operational benefits of Spark Connect
-
-With this new architecture, Spark Connect mitigates several multi-tenant
-operational issues:
-
-**Stability**: Applications that use too much memory will now only impact their
-own environment as they can run in their own processes. Users can define their
-own dependencies on the client and don't need to worry about potential
conflicts
-with the Spark driver.
-
-**Upgradability**: The Spark driver can now seamlessly be upgraded
independently
-of applications, for example to benefit from performance improvements and
security fixes.
-This means applications can be forward-compatible, as long as the server-side
RPC
-definitions are designed to be backwards compatible.
-
-**Debuggability and observability**: Spark Connect enables interactive
debugging
-during development directly from your favorite IDE. Similarly, applications can
-be monitored using the application's framework native metrics and logging
libraries.
-
-# How to use Spark Connect
-
-Spark Connect is available and supports PySpark and Scala
-applications. We will walk through how to run an Apache Spark server with Spark
-Connect and connect to it from a client application using the Spark Connect
client
-library.
-
-## Download and start Spark server with Spark Connect
+
+Spark Connect ships with every Spark release since 3.4 and supports PySpark
and Scala
+applications. For what Spark Connect is and how it differs from classic Spark,
see the
+[Spark Connect Overview](spark-connect-overview.html).
+
+* This will become a table of contents (this text will be scraped).
+{:toc}
+
+## Starting a Spark Connect server
First, download Spark from the
[Download Apache Spark](https://spark.apache.org/downloads.html) page. Choose
the
@@ -117,22 +40,44 @@ tar -xvf spark-{{site.SPARK_VERSION_SHORT}}-bin-hadoop3.tgz
In a terminal window, go to the `spark` folder in the location where you
extracted
Spark before and run the `start-connect-server.sh` script to start Spark
server with
-Spark Connect, like in this example:
+Spark Connect. If you already have Spark installed and `SPARK_HOME` defined,
you can use that too.
```bash
./sbin/start-connect-server.sh
+
+# alternately
+"$SPARK_HOME/sbin/start-connect-server.sh"
```
Alternatively, `./bin/spark-connect-shell` starts an interactive Scala shell
with the Connect server hosted inside the shell process itself.
-Make sure to use the same version of the package as the Spark version you
-downloaded previously. In this example, Spark {{site.SPARK_VERSION_SHORT}}
with Scala 2.13.
+The script accepts the same options as `spark-submit`, so `--master`,
`--jars`, `--packages`
+and `--conf` work as they do for any other Spark application. Everything that
the server
+reads at startup, such as `spark.sql.extensions`, `spark.jars`,
`spark.jars.packages` and the
+JARs that catalogs load, is set here. Clients can only change runtime
configuration of their own
+session; that includes defining a catalog (`spark.sql.catalog.<name>`) whose
JAR is already on the
+server.
+
+By default the server listens on port 15002 on all interfaces and runs as a
background daemon
+(`./sbin/stop-connect-server.sh` stops it). Pass `--wait` as the first
argument to keep it in
+the foreground instead, for example as a container entrypoint or under a
process supervisor. With
+`--wait`, the script sets `SPARK_NO_DAEMONIZE=1`, writes no PID file and sends
the logs to standard
+output. `spark.connect.grpc.binding.address` restricts the listening interface
and
+`spark.connect.grpc.binding.port` changes the port:
-Now Spark server is running and ready to accept Spark Connect sessions from
client
-applications. In the next section we will walk through how to use Spark Connect
-when writing client applications.
+```bash
+./sbin/start-connect-server.sh --wait \
+ --conf spark.connect.grpc.binding.address=127.0.0.1 \
+ --conf spark.connect.grpc.binding.port=15002
+```
+
+Spark does not retry another port when the configured one is taken
+(`spark.connect.grpc.port.maxRetries` defaults to 0), so a port conflict fails
the server with a
+`java.net.BindException` instead of silently moving it. A daemonized server
logs to `logs/` under
+the Spark folder (or `SPARK_LOG_DIR`), and the Spark UI of the server, at port
4040 by default, has a
+**Connect** tab listing sessions and requests.
-## Use Spark Connect for interactive analysis
+## Interactive analysis with Spark Connect
<div class="codetabs">
<div data-lang="python" markdown="1">
@@ -152,21 +97,21 @@ code change needed to start using Spark Connect.
In a terminal window, set the `SPARK_REMOTE` environment variable to point to
the
local Spark server you started previously on your computer:
-{% highlight bash %}
+```bash
export SPARK_REMOTE="sc://localhost"
-{% endhighlight %}
+```
And start the Spark shell as usual:
-{% highlight bash %}
+```bash
./bin/pyspark
-{% endhighlight %}
+```
The PySpark shell is now connected to Spark using Spark Connect as indicated
in the welcome message:
-{% highlight python %}
+```python
Client connected to the Spark Connect server at localhost
-{% endhighlight %}
+```
### Specify Spark Connect when creating Spark session
@@ -180,29 +125,29 @@ To launch the PySpark shell with Spark Connect, simply
include the `remote`
parameter and specify the location of your Spark server. We are using
`localhost`
in this example to connect to the local Spark server we started previously:
-{% highlight bash %}
+```bash
./bin/pyspark --remote "sc://localhost"
-{% endhighlight %}
+```
And you will notice that the PySpark shell welcome message tells you that
you have connected to Spark using Spark Connect:
-{% highlight python %}
+```python
Client connected to the Spark Connect server at localhost
-{% endhighlight %}
+```
You can also check the Spark session type. If it includes `.connect.` you
are using Spark Connect as shown in this example:
-{% highlight python %}
+```python
SparkSession available as 'spark'.
>>> type(spark)
<class 'pyspark.sql.connect.session.SparkSession'>
-{% endhighlight %}
+```
Now you can run PySpark code in the shell to see Spark Connect in action:
-{% highlight python %}
+```python
>>> columns = ["id", "name"]
>>> data = [(1,"Sarah"), (2,"Maria")]
>>> df = spark.createDataFrame(data).toDF(*columns)
@@ -213,19 +158,19 @@ Now you can run PySpark code in the shell to see Spark
Connect in action:
| 1|Sarah|
| 2|Maria|
+---+-----+
-{% endhighlight %}
+```
</div>
-<div data-lang="scala" markdown="1">
+<div data-lang="scala" markdown="1">
For the Scala shell, we use an Ammonite-based REPL. Otherwise, very similar
with PySpark shell.
-{% highlight bash %}
+```bash
./bin/spark-shell --remote "sc://localhost"
-{% endhighlight %}
+```
A greeting message will appear when the REPL successfully initializes:
-{% highlight bash %}
+```bash
Welcome to
____ __
/ __/__ ___ _____/ /__
@@ -235,52 +180,73 @@ Welcome to
Type in expressions to have them evaluated.
Spark session available as 'spark'.
-{% endhighlight %}
+```
By default, the REPL will attempt to connect to a local Spark Server.
Run the following Scala code in the shell to see Spark Connect in action:
-{% highlight scala %}
+```scala
@ spark.range(10).count
res0: Long = 10L
-{% endhighlight %}
+```
-### Configure client-server connection
+</div>
+</div>
-By default, the REPL will attempt to connect to a local Spark Server on port
15002.
-The connection, however, may be configured in several ways as described in
this configuration
-[reference](https://github.com/apache/spark/blob/master/sql/connect/docs/client-connection-string.md).
+## Connection strings
-#### Set SPARK_REMOTE environment variable
+By default, the shells and the `remote()` builder attempt to connect to a
local Spark Server on
+port 15002. The connection, however, may be configured in several ways as
described in this
+configuration
[reference](https://github.com/apache/spark/blob/master/sql/connect/docs/client-connection-string.md).
+A connection string has the form `sc://host:port/;param1=value;param2=value`:
the scheme is
+always `sc://`, the path component must stay empty because gRPC uses the
HTTP/2 path for its own
+method names, and parameters such as `token`, `use_ssl`, `user_id` and
`user_agent` follow a `/;`
+separator. Setting `token` turns on TLS for any host except `localhost`; to
use TLS with
+`localhost`, set `use_ssl=true` as well.
+
+In the Python client, a parameter value cannot contain a literal `/`, because
its parser reads
+everything from the first `/` as the path:
+
+```python
+SparkSession.builder.remote("sc://localhost:15002/;user_agent=myapp/1").getOrCreate()
+# [INVALID_CONNECT_URL] Invalid URL for Spark Connect:
+# The path component '/;user_agent=myapp/1' must be empty.
+```
+
+Write the `/` as `%2F` instead: `user_agent=myapp%2F1` is accepted and read as
`myapp/1`.
+
+### Set SPARK_REMOTE environment variable
The SPARK_REMOTE environment variable can be set on the client machine to
customize the client-server
connection that is initialized at REPL startup.
-{% highlight bash %}
+```bash
export SPARK_REMOTE="sc://myhost.com:443/;token=ABCDEFG"
./bin/spark-shell
-{% endhighlight %}
+```
-or
+### Configure programmatically with a connection string
-{% highlight bash %}
-SPARK_REMOTE="sc://myhost.com:443/;token=ABCDEFG" spark-connect-repl
-{% endhighlight %}
+The connection may also be programmatically created using
_SparkSession#builder_ as in this example:
-#### Configure programmatically with a connection string
+<div class="codetabs">
-The connection may also be programmatically created using
_SparkSession#builder_ as in this example:
+<div data-lang="python" markdown="1">
+```python
+from pyspark.sql import SparkSession
+spark =
SparkSession.builder.remote("sc://myhost.com:443/;token=ABCDEFG").getOrCreate()
+```
+</div>
-{% highlight scala %}
+<div data-lang="scala" markdown="1">
+```scala
@ import org.apache.spark.sql.SparkSession
-@ val spark =
SparkSession.builder.remote("sc://localhost:443/;token=ABCDEFG").getOrCreate()
-{% endhighlight %}
-
+@ val spark =
SparkSession.builder.remote("sc://myhost.com:443/;token=ABCDEFG").getOrCreate()
+```
</div>
</div>
## Faster local iteration with a persistent Connect server
-
When you develop or test locally with
```python
@@ -293,6 +259,13 @@ process. Every `python script.py` invocation (or every new
test worker process)
the one-time startup cost -- JVM warmup, `SparkContext` construction, and
Connect server boot --
which can take a few seconds and makes a quick edit/run loop feel slow.
+The in-process server binds port 15002 by default and the client dials
`sc://localhost`,
+so if another Spark Connect server is already listening on that port (a
container, or a server
+left running from an earlier session) the start fails with
+`java.net.BindException: Failed to bind to address 0.0.0.0/0.0.0.0:15002`.
Moving the port with
+`spark.connect.grpc.binding.port` does not help here, because the client would
still dial
+15002 and reach the other server; stop the other server or connect to it by
URL instead.
+
To amortize that cost across runs, start one persistent local Spark Connect
server and point
every run at it:
@@ -345,8 +318,7 @@ backed by the shared `SparkContext` (the persistent
catalog/warehouse, global te
cached datasets) *is* shared across runs, so namespace per-run databases or
clear that state
yourself if your runs must be fully isolated.
-## Use Spark Connect in standalone applications
-
+## Spark Connect in standalone applications
<div class="codetabs">
@@ -354,27 +326,27 @@ yourself if your runs must be fully isolated.
First, install PySpark with `pip install
pyspark-client=={{site.SPARK_VERSION_SHORT}}` or if building a packaged PySpark
application/library,
add it your setup.py file as:
-{% highlight python %}
+```python
install_requires=[
'pyspark-client=={{site.SPARK_VERSION_SHORT}}'
]
-{% endhighlight %}
+```
When writing your own code, include the `remote` function with a reference to
your Spark server when you create a Spark session, as in this example:
-{% highlight python %}
+```python
from pyspark.sql import SparkSession
spark = SparkSession.builder.remote("sc://localhost").getOrCreate()
-{% endhighlight %}
+```
For illustration purposes, we’ll create a simple Spark Connect application,
SimpleApp.py:
-{% highlight python %}
+```python
"""SimpleApp.py"""
from pyspark.sql import SparkSession
-logFile = "YOUR_SPARK_HOME/README.md" # Should be some file on your system
+logFile = "YOUR_SPARK_HOME/README.md" # a path the server can read
spark =
SparkSession.builder.remote("sc://localhost").appName("SimpleApp").getOrCreate()
logData = spark.read.text(logFile).cache()
@@ -384,35 +356,38 @@ numBs =
logData.filter(logData.value.contains('b')).count()
print("Lines with a: %i, lines with b: %i" % (numAs, numBs))
spark.stop()
-{% endhighlight %}
+```
This program just counts the number of lines containing ‘a’ and the number
containing ‘b’ in a text file.
Note that you’ll need to replace YOUR_SPARK_HOME with the location where Spark
is installed.
We can run this application with the regular Python interpreter as follows:
-{% highlight python %}
+```python
# Use the Python interpreter to run your application
$ python SimpleApp.py
...
Lines with a: 72, lines with b: 39
-{% endhighlight %}
+```
</div>
<div data-lang="scala" markdown="1">
To use Spark Connect as part of a Scala application/project, we first need to
include the right dependencies.
Using the `sbt` build system as an example, we add the following dependencies
to the `build.sbt` file:
-{% highlight sbt %}
+```sbt
libraryDependencies += "org.apache.spark" %% "spark-connect-client-jvm" %
"{{site.SPARK_VERSION_SHORT}}"
-{% endhighlight %}
+```
+
+Depend on `spark-connect-client-jvm` only, and start the JVM with
+`--add-opens=java.base/java.nio=ALL-UNNAMED`.
When writing your own code, include the `remote` function with a reference to
your Spark server when you create a Spark session, as in this example:
-{% highlight scala %}
+```scala
import org.apache.spark.sql.SparkSession
val spark = SparkSession.builder().remote("sc://localhost").getOrCreate()
-{% endhighlight %}
+```
**Note**: Operations that reference User Defined Code such as UDFs, filter,
map, etc require a
@@ -420,7 +395,7 @@ val spark =
SparkSession.builder().remote("sc://localhost").getOrCreate()
to be registered to pickup and upload any required classfiles. Also, any JAR
dependencies must be uploaded to the server using `SparkSession#AddArtifact`.
Example:
-{% highlight scala %}
+```scala
import org.apache.spark.sql.connect.client.REPLClassDirMonitor
// Register a ClassFinder to monitor and upload the classfiles from the build
output.
val classFinder = new REPLClassDirMonitor(<ABSOLUTE_PATH_TO_BUILD_OUTPUT_DIR>)
@@ -428,7 +403,7 @@ spark.registerClassFinder(classFinder)
// Upload JAR dependencies
spark.addArtifact(<ABSOLUTE_PATH_JAR_DEP>)
-{% endhighlight %}
+```
Here, `ABSOLUTE_PATH_TO_BUILD_OUTPUT_DIR` is the output directory where the
build system writes classfiles into
and `ABSOLUTE_PATH_JAR_DEP` is the location of the JAR on the local file
system.
@@ -438,51 +413,48 @@ one may implement their own class extending `ClassFinder`
for customized search
</div>
</div>
-For more information on application development with Spark Connect as well as
extending Spark Connect
-with custom functionality, see [Application Development with Spark
Connect](app-dev-spark-connect.html).
-# Client application authentication
+For extending Spark Connect with custom server-side functionality, see
+[Extending Spark with Spark Server Libraries](spark-connect-server-libs.html).
-While Spark Connect does not have built-in authentication, it is designed to
-work seamlessly with your existing authentication infrastructure. Its gRPC
-HTTP/2 interface allows for the use of authenticating proxies, which makes
-it possible to secure Spark Connect without having to implement authentication
-logic in Spark directly.
+## Switching between Spark Connect and Spark Classic
-# What is supported
+There are three ways to get a Spark Connect session, depending on where the
server runs:
-**PySpark**: Since Spark 3.4, Spark Connect supports most PySpark APIs,
including
-[DataFrame](api/python/reference/pyspark.sql/dataframe.html),
-[Functions](api/python/reference/pyspark.sql/functions.html), and
-[Column](api/python/reference/pyspark.sql/column.html). However,
-some APIs such as
[SparkContext](api/python/reference/api/pyspark.SparkContext.html)
-and [RDD](api/python/reference/api/pyspark.RDD.html) are not supported.
-You can check which APIs are currently
-supported in the [API reference](api/python/reference/index.html)
documentation.
-Supported APIs are labeled "Supports Spark Connect" so you can check whether
the
-APIs you are using are available before migrating existing code to Spark
Connect.
+- An `sc://` connection string, given as `spark.remote`, `--remote` or the
`remote()` argument,
+ connects to a server that is already running: a shared cluster's Spark
Connect endpoint, or the
+ [persistent local
server](#faster-local-iteration-with-a-persistent-connect-server) during
+ development.
+- A `local[...]` or `local-cluster[...]` value of `spark.remote` or `--remote`
starts a local
+ Spark Connect server for the application and connects to it. Use it for
local development and
+ tests.
+- `--master ...` together with `spark.api.mode=connect` starts a Spark Connect
server in the
+ application's driver, running on that master, and runs the application
against it. It accepts
+ the same master URLs as Spark Classic, such as `spark://`, so an existing
Spark Classic
+ application switches to Spark Connect without code changes.
-**Scala**: Since Spark 3.5, Spark Connect supports most Scala APIs, including
-[Dataset](api/scala/org/apache/spark/sql/Dataset.html),
-[functions](api/scala/org/apache/spark/sql/functions$.html),
-[Column](api/scala/org/apache/spark/sql/Column.html),
-[Catalog](api/scala/org/apache/spark/sql/catalog/Catalog.html) and
-[KeyValueGroupedDataset](api/scala/org/apache/spark/sql/KeyValueGroupedDataset.html).
+Depending on the value of `spark.api.mode`, the application runs in either
Spark Classic or Spark
+Connect mode. Set it in the session builder:
-User-Defined Functions (UDFs) are supported, by default for the shell and in
standalone applications with
-additional set-up requirements.
+```python
+from pyspark.sql import SparkSession
-Majority of the Streaming API is supported, including
-[DataStreamReader](api/scala/org/apache/spark/sql/streaming/DataStreamReader.html),
-[DataStreamWriter](api/scala/org/apache/spark/sql/streaming/DataStreamWriter.htmll),
-[StreamingQuery](api/scala/org/apache/spark/sql/streaming/StreamingQuery.html)
and
-[StreamingQueryListener](api/scala/org/apache/spark/sql/streaming/StreamingQueryListener.html).
+SparkSession.builder.config("spark.api.mode",
"connect").master("...").getOrCreate()
+```
-APIs such as [SparkContext](api/scala/org/apache/spark/SparkContext.html)
-and [RDD](api/scala/org/apache/spark/rdd/RDD.html) are unsupported in Spark
Connect.
+or when submitting a Scala or PySpark application:
-Support for more APIs is planned for upcoming Spark releases.
+```bash
+spark-submit --master "..." --conf spark.api.mode=connect
+```
+
+## Client application authentication
-# Routing through a shared ingress or reverse proxy
+Spark Connect has no user-facing authentication of its own. Its gRPC HTTP/2
+interface allows for the use of authenticating proxies, which makes it possible
+to secure Spark Connect without having to implement authentication logic in
+Spark directly.
+
+## Routing through a shared ingress or reverse proxy
When several services share a single hostname behind a Kubernetes Ingress (or
another
reverse proxy), it is tempting to give each service a URL path prefix (for
example
@@ -503,21 +475,21 @@ This is the approach the gRPC maintainers recommend for
this scenario
The example below uses the Python client, which exposes gRPC channel options
directly:
-{% highlight python %}
+```python
from pyspark.sql.connect.session import SparkSession
from pyspark.sql.connect.client import DefaultChannelBuilder
cb = DefaultChannelBuilder("sc://myhost.com:443")
cb.setChannelOption("grpc.default_authority", "sparkconnect") # routing tag
spark = SparkSession.builder.channelBuilder(cb).getOrCreate()
-{% endhighlight %}
+```
A corresponding Kubernetes Ingress routes on that tag and keeps the service at
path `/`
(no subpath, no rewrite). Note the routing tag must be a lowercase
[RFC 1123](https://datatracker.ietf.org/doc/html/rfc1123) name, since a
Kubernetes Ingress
`host:` requires one:
-{% highlight yaml %}
+```yaml
spec:
rules:
- host: sparkconnect # matches grpc.default_authority
@@ -529,7 +501,7 @@ spec:
service:
name: spark-connect-server
port: { number: 15002 }
-{% endhighlight %}
+```
**Over TLS**, gRPC uses the `:authority` as the certificate-verification name
by default,
so overriding it with a routing tag would fail verification (the tag is not in
the server
@@ -537,12 +509,12 @@ certificate's SAN). Keep the two names separate: set
`grpc.ssl_target_name_overr
real server hostname (used for certificate verification and SNI) and
`grpc.default_authority`
to the routing tag.
-{% highlight python %}
+```python
cb = DefaultChannelBuilder("sc://myhost.com:443/;use_ssl=true")
cb.setChannelOption("grpc.ssl_target_name_override", "myhost.com") #
certificate verification / SNI
cb.setChannelOption("grpc.default_authority", "sparkconnect") # routing
tag
spark = SparkSession.builder.channelBuilder(cb).getOrCreate()
-{% endhighlight %}
+```
`use_ssl=true` verifies the server certificate against the system's trusted CA
store. If your
gateway's certificate is issued by a CA the client does not trust by default
(a self-signed or
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]