How-to guides

Spark runtimeDownload PDF (3.0 MB)

Read from a connection#

Connections are created once in Groundzero (credentials stay in the connection) and referenced by name from code. Every connector adds read*, execute* and write* methods to the Spark session; the exact set depends on the connector (see the connector table in the API reference).

Pattern: the first argument to every read or execute method is connName, the name of the connection. For write methods the DataFrame comes first, followed by connName.

Object storage#

python
from GZ.SparkUtils import sparkSession

spark = sparkSession("ReadSales")

raw = spark.readS3(
    connName="acme-s3",
    fileName="landing/sales/2026/",
    format="csv",
    options={"header": "true", "inferSchema": "true"},
)
raw.printSchema()

readS3 builds the path s3a://<bucket>/<fileName> from the connection's bucket. Pass a schema as schema= to skip inference on large inputs.

Relational databases#

All the JDBC-based connectors (PostgreSQL, MySQL, SQL Server, Oracle, Redshift, Teradata, ClickHouse, Databricks, Trino and others) share one reader:

python
orders = spark.readJDBC(
    connName="acme-postgres",
    query="SELECT order_id, region, amount FROM sales.orders "
    "WHERE order_date >= DATE '2026-01-01'",
)

Run DDL or DML (create, insert, update, delete) with executeJDBC:

python
spark.executeJDBC(
    connName="acme-postgres",
    query="DELETE FROM sales.staging_orders WHERE loaded = true",
)

Push work to the database

readJDBC sends your query to the database as a subquery, so filters and aggregations in the SQL run there. Select only the columns and rows you need before Spark sees them.

Snowflake, BigQuery and other warehouses#

python
df = spark.executeSnowflake(
    connName="acme-snowflake",
    query="SELECT customer_id, SUM(total) AS spend FROM orders GROUP BY 1",
)

Most warehouse connectors follow the same executeX(connName, query) shape and return a DataFrame, plus a writeX(df, connName, tableName, ...) writer. See the connector table for the exact method names.

Streams#

python
events = spark.readKafka(
    connName="acme-kafka",
    topic="orders.created",
    startingOffsets="earliest",
)

readKafka returns a streaming DataFrame. Streaming writers such as writeKafka, writeStreamToS3 and writeGzLakehouse(..., streaming=True) require a checkpointLocation.

Other helpers for credentials#

If you need the native client library rather than a Spark DataFrame (for example boto3, pymongo or a SQLAlchemy engine), use the client factory:

python
from GZ.Client import getClient

client = getClient()
s3 = client.getS3Client("acme-s3")
buckets = s3.list_objects_v2(Bucket="acme-data", MaxKeys=5)

Credentials are never visible to your script. The factory returns an object that is already authenticated.

Query and write Lakehouse (Iceberg) tables#

Groundzero Lakehouse tables are Apache Iceberg tables. A GZLAKEHOUSE Groundzero Lakehouse tables are Apache Iceberg tables. A GZLAKEHOUSE connection** names the warehouse and the default database. Two methods cover most work: executeQuery to read with SQL, and writeGzLakehouse to append or overwrite. To check it worked, call orders.show() or read the table back with executeQuery.

Query with SQL#

python
from GZ.SparkUtils import sparkSession

spark = sparkSession("LakehouseRead", siteName="acme")

orders = spark.executeQuery(
    connName="acme-lakehouse",
    sqlQuery="""
        SELECT region, SUM(amount) AS total
        FROM sales.orders
        GROUP BY region
    """,
)
orders.show()

Always qualify tables as database.table. The database name must be one you can see in the Lakehouse pages.

Name the site for lakehouse connections

A lakehouse connection routes every call to a site. Groundzero normally finds your site by itself. If it cannot, pass siteName="your-site" to sparkSession (applies to all such connections), pass siteNames={"connection-name": "site"} for one site per connection, or pass siteName= to the individual call. Otherwise the call raises ValueError: siteName is required for GZLAKEHOUSE connection.

Statements that only read data (SELECT, SHOW, DESCRIBE, EXPLAIN) need no extra check. Statements that change data are checked against your permission on each table first.

Write a table#

python
daily = orders.withColumnRenamed("total", "daily_total")

spark.writeGzLakehouse(
    df=daily,
    connName="acme-lakehouse",
    tableName="orders_daily",
    database="sales",
    mode="append",
)

For connections with a lakehouse endpoint, mode must be append or overwrite. overwrite replaces the snapshot of an existing table. External (read-only) lakehouse connections reject all writes.

Stream into a table#

python
query = spark.writeGzLakehouse(
    df=events_df,
    connName="acme-lakehouse",
    tableName="orders_stream",
    database="sales",
    streaming=True,
    checkpointLocation="s3://acme-data/checkpoints/orders_stream",
    outputMode="append",
    trigger={"availableNow": True},
)

Create the target table, including its partition specification, before streaming into it. partitionBy is rejected for streaming writes.

Check your connection first#

verifyLakehouseConnection checks that the connection reaches the expected warehouse. It turns a routing problem into an immediate, readable error:

python
info = spark.verifyLakehouseConnection("acme-lakehouse", siteName="acme")
print(info["warehouse"], info["site_used"])

Bulk-load from Snowflake or Redshift#

For large one-time loads, let the source warehouse unload Parquet files directly into the lakehouse table's storage and register them with one Iceberg commit. No row passes through Spark:

python
summary = spark.bulkLoadGzLakehouseFromSnowflake(
    connName="acme-snowflake",
    query="SELECT * FROM analytics.orders WHERE order_date >= '2026-01-01'",
    lakehouseConn="acme-lakehouse",
    tableName="orders_history",
    database="sales",
    mode="overwrite",
    siteName="acme",
)
print(summary)

Work with outputs and previews#

The runtime turns your result into a preview that the UI pages through.

  • Assign the DataFrame you want to show to the top-level variable outputDF.
  • For a Spark DataFrame, the runtime reads up to 100,000 rows. If your result has more rows, the preview is the first 100,000.
  • A pandas DataFrame is converted to a list of records. Any list of dictionaries also works.
  • The schema shown in the preview is taken from outputDF.
  • When the same code runs again with the same inputs within a short period, the runtime may serve the preview from its cache. Results from governed lakehouse tables are cached per caller policy, so users share cached rows only when their policies allow it.
python
import pandas as pd

summary = pd.DataFrame(
    {"metric": ["rows", "regions"], "value": [1_250_000, 4]}
)
outputDF = summary

Keep previews fast

Order and limit the result before you assign it to outputDF. A deterministic plan without shuffles lets the runtime return the first page without reading the whole preview. Joins, aggregates and sorts need the whole result.

Dataset runs page the preview with a page size that defaults to 1,000 rows and is capped at 10,000.

Use parameters and placeholders#

Groundzero replaces a fixed set of placeholders in your code with run-time values before the script executes. They are replaced as text, so write them where a Python string expression is valid.

python
from GZ.SparkUtils import sparkSession

spark = sparkSession("Parameters")

run_started = {STRTTM}
site = {SITENM}
print("Started:", run_started, "for site", site)

The line run_started = {STRTTM} becomes run_started = "'2026-10-01 09:30:00'". The substituted value is already quoted for SQL, so it can be concatenated into a statement:

python
sql = "SELECT * FROM sales.orders WHERE created_at >= " + {STRTTM}
df = spark.executeQuery("acme-lakehouse", sql)

The placeholders are listed in the API reference. The ${NAME} spelling is also accepted.

Placeholders are not Python f-string fields

Write "... >= " + {STRTTM}, not f"... >= {STRTTM}". Inside a string literal the replacement text would break the quoting.

Chain jobs#

A job that was submitted with sub-jobs can run them in sequence from code using executeJob:

python
from GZ.JobUtils import executeJob

results = executeJob(["load_orders", "build_marts"])
print(list(results))

Each sub-job runs with the same restrictions as a normal job. If one fails, executeJob raises and the remaining jobs do not run.

Schedule through ETL jobs#

  1. Save the job with its runtime and compute.
  2. Open the scheduler for the job and set the frequency, start and stop times.
  3. Choose the RTE with the runtime picker.

If you set a stop time, the session ends at that time and aborts any job still running. Use a stop time as a safety cap for long-running streaming jobs.

When a job finishes, Groundzero sends the notification configured for the job's status (success or failure), if there is one. Its subject and body can use the same placeholders. From code, you can also send your own mail (see sendEmail).

Install and use extra packages#

Use this when your code needs a library that the runtime does not include. Check Installed packages first, because most common libraries are already there.

Need Route
Try a package in a notebook %pip install name in a notebook cell
Machine-learning libraries Pick the scikit-learn, PyTorch or TensorFlow variant
Packages for every job A custom runtime that extends a Spark runtime

Notebook installs#

In a notebook you can install a package for the life of the session:

%pip install rapidfuzz

To check it worked, import rapidfuzz in the next cell. The package disappears when the session ends. Job scripts run with restrictions, so do not install packages from inside a job script.

Custom runtimes#

A custom runtime is a Spark runtime with extra Python packages added. Administrators create it on the Custom RTE page:

  1. Prepare a requirements.txt with one pip requirement per line.
  2. Select Add custom RTE, choose the Base Image to extend (for example a Spark variant), give the runtime a Name, and upload the file.
  3. Wait for the build. The table on the page shows each runtime's name, creator, creation date and build Status.
  4. When the status shows success, choose the new runtime in the runtime picker.

An example requirements.txt:

splink
sqlparse
s3fs

Pick the closest base

Extend the Spark variant that already has most of what you need (for example the scikit-learn variant for model work) so you only add the difference.

If the build fails, the Status column shows the failure. Check that each package name and version in requirements.txt exists and supports Python 3.12.

Tune performance#

Partitions and shuffles#

Spark runs one task per partition. Match the partition count to the cores you have: too few leaves workers idle, too many wastes time on scheduling.

python
from GZ.SparkUtils import sparkSession

spark = sparkSession("Tuned", **{"spark.sql.shuffle.partitions": "64"})

df = spark.executeQuery("acme-lakehouse", "SELECT * FROM sales.orders")
df = df.repartition(64, "region")

Any keyword argument you pass to sparkSession is applied as a Spark setting. Setting names contain dots, so pass them with **{...} as shown. Settings apply only when the session is first created. A reused session ignores them.

Defaults the runtime already sets:

Setting Value
spark.serializer Kryo, buffer up to 1 GB
spark.driver.maxResultSize 0 (unlimited)
spark.network.timeout 600 seconds
spark.sql.broadcastTimeout 600 seconds
spark.sql.adaptive.enabled true when a lakehouse connection exists
spark.dynamicAllocation.enabled true, executors idle out after 120 seconds

Memory#

  • Executor memory is set from the compute size (65 percent of worker memory, at most worker memory minus 1 GiB). To get more, pick a larger compute size.
  • Avoid collect() and toPandas() on large DataFrames: the data lands in the driver's memory. Aggregate or limit first.
  • Cache a DataFrame (df.cache()) only when several actions reuse it, and release it with df.unpersist().

The driver has no result limit

spark.driver.maxResultSize is 0, so an oversized collect() fails with an out-of-memory error instead of a friendly limit message.

Arrow#

Arrow speeds up transfers between Spark and Python.

  • Use the *Arrow connector methods (for example readRESTArrow, readSalesforceArrow, readSFTPArrow) for Python-side API connectors. They fetch and write through Arrow tables, and many accept a columns list to prune data.
  • Enable Arrow for toPandas() and pandas UDFs with spark.conf.set("spark.sql.execution.arrow.pyspark.enabled", "true").
  • Dataset previews of nested columns are read through Arrow for you, so you need no setting for that.

Read less#

  • Select columns and filter early; Iceberg and Parquet push both down.
  • Prefer Parquet or Iceberg over CSV for intermediate data.
  • Pass an explicit schema= to readS3 to skip schema inference.

Log from your job#

Everything your script writes to standard output or standard error is captured and shown in the job log, tagged with the job's execution identifier. Use print or the standard logging module.

python
import logging

log = logging.getLogger("orders-job")
log.warning("Loaded %d rows", orders.count())
print("done")

sparkSession(appName, logLevel) sets the Spark log level (ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF, TRACE). The default is WARN. Errors raised by your script are reported with the exception type, message and the line number in your code, for example ValueError: bad region at line 14.

The runtime also collects Spark metrics for each run (tasks, stages, shuffle and spill, GC time, input and output records) and attaches them to the execution so you can inspect them with the run details. No code is needed for that.

Check data quality#

Qualipilot runs deterministic checks inside Spark and, optionally, sends a compact aggregate to an LLM connection for a narrative summary. Row samples and top values are never sent.

python
from GZ.SparkUtils import sparkSession
from qualipilot import CheckConfig, QualipilotConfig
from qualipilot.models.config import ColumnRange

spark = sparkSession("QualityCheck")
orders = spark.createDataFrame(
    [(1001, "ana@example.com", 125.0), (1002, None, -25.0)],
    ["order_id", "customer_email", "amount"],
)
config = QualipilotConfig(
    checks=CheckConfig(
        required_columns=["order_id", "customer_email", "amount"],
        column_ranges={"amount": ColumnRange(min=0, max=10_000)},
    )
)
report = spark.runDataQualityChecks(
    df=orders, connectionName="acme-openai", config=config
)
print(report.to_json())
spark.saveDataQualityReport(report, "reports/orders.html", "html")

Parse PDFs and run Agents over documents#

parsePDF extracts one document from S3, parsePDFCorpus extracts a folder restartably, and invokeAgentPDFCorpus runs a Groundzero Agent over every document in a prefix. Corpus runs are content-addressed: re-running the same source and output prefix skips page ranges that are already committed.

python
result = spark.parsePDFCorpus(
    s3ConnName="acme-s3",
    sourcePrefix="incoming/policies/",
    outputS3ConnName="acme-s3",
    outputPrefix="pdf-results/policies",
    pageRangeSize=64,
)
print(result["status"], result["documentCount"], result["manifestUri"])

See the API reference for the full parameter list and the examples gallery for an end-to-end Agent run.