How-to guides
Create and configure a session#
duckSession() is the single entry point. It returns a DuckSession: a DuckDB
connection plus every connector method (readS3File, executeJdbc,
readGzLakehouse and so on).
from GZ.DuckDBUtils import duckSession
# Defaults: in-memory database, threads and memory sized from your compute.
session = duckSession()
# Persist the database to a file, pin resources, set DuckDB options.
session = duckSession(
duckdbPath="/tmp/work.duckdb",
logLevel="WARNING",
threads=4,
memory_limit="6GB",
http_timeout="120",
)Any extra keyword argument becomes a DuckDB SET name='value' statement, so
every documented DuckDB setting is available. Settings that fail are logged as
warnings and skipped.
A session is also a context manager, which closes the connection and releases connector clients when the block ends:
from GZ.DuckDBUtils import duckSession
with duckSession(logLevel="WARNING") as session:
session.query("CREATE TABLE t AS SELECT range AS n FROM range(5)")
print(session.query("SELECT sum(n) AS total FROM t", returnFormat="pandas"))One session per run
Create the session once at the top of your code and reuse it. Each call to
duckSession() opens a new DuckDB connection with its own tables, secrets
and memory budget.
Read from connections#
Every connector method follows the same conventions:
- the first argument is
connName, the name of a Groundzero connection; returnFormatis"duckdb"(default, a lazy relation),"pandas"or"arrow";targetDuckdbTable, when given, also registers the result as a table or view with that name so SQL can refer to it.
Object storage (S3, GCS, Azure Blob)#
from GZ.DuckDBUtils import duckSession
session = duckSession()
# One Parquet file
orders = session.readS3File(
connName="sales_s3",
bucketName="acme-retail-data",
filePath="raw/orders/2026-09-30.parquet",
)
# Many files with a glob, registered under a name
session.readS3File(
connName="sales_s3",
s3FullUrl="s3://acme-retail-data/raw/orders/*.parquet",
targetDuckdbTable="orders_all",
)
# CSV with reader options; keys are DuckDB's own option names
customers = session.readS3File(
connName="sales_s3",
bucketName="acme-retail-data",
filePath="raw/customers.csv",
fileType="csv",
readOptions={"delim": ",", "header": True},
)
print(session.query("SELECT count(*) AS n FROM orders_all",
returnFormat="pandas"))readS3File retries a failing read in two more modes before giving up: first
with every column read as text (all_varchar), then with malformed rows ignored
(ignore_errors). CSV reads default to a header row, a double quote character,
null padding, relaxed strictness and a 100,000-row type-detection sample unless
you override those options.
readGcsFile(connName, bucketName, filePath, fileType, . and
readAzureBlob(connName, containerName, blobName, fileType, . take the same
fileType, readOptions, targetDuckdbTable and returnFormat arguments.
SQL databases (JDBC)#
executeJdbc runs a query on PostgreSQL, MySQL, Oracle, SQL Server, Db2,
Redshift, CockroachDB, SAP HANA, TimescaleDB, Exasol and SQLite connections and
loads the result into DuckDB. PostgreSQL, SQLite, Redshift and CockroachDB
results stream in Arrow batches.
customers = session.executeJdbc(
connName="orders_pg",
sqlQuery="""
SELECT customer_id, segment, signup_date
FROM public.customers
WHERE signup_date >= DATE '2025-01-01'
""",
targetDuckdbTable="customers",
)Cloud warehouses#
# Snowflake: results stream into a DuckDB table in Arrow batches.
n_rows = session.readSnowflake(
conn_name="wh_snowflake",
sql_query="SELECT * FROM ANALYTICS.PUBLIC.ORDERS",
target_duckdb_table="orders_sf",
returnFormat="row_count",
)
# BigQuery
events = session.readBigQuery(
connName="analytics_bq",
query="SELECT user_id, event FROM `acme.web.events` LIMIT 1000",
)Note that readSnowflake uses snake_case argument names and requires the
target table name. Because it streams one Arrow batch at a time, it can load
tables far larger than Python memory.
APIs and other sources#
executeREST calls an HTTP API configured as a REST connection and flattens the
JSON records into a relation. readKafka, readMongo, readDynamoDB,
readSalesforce, readCassandra and the rest of the connector table in the API
reference follow the same pattern.
tickets = session.executeREST(
connName="support_api",
endpoint="/v2/tickets",
params={"status": "open"},
resultPath="data.items",
maxPages=5,
)Query across sources#
Because every read returns a DuckDB relation, you can join data from different systems in one statement. Register each relation under a name, then use SQL.
from GZ.DuckDBUtils import duckSession
session = duckSession()
orders = session.readS3File(
"sales_s3", "acme-retail-data", "raw/orders/2026-09-30.parquet"
)
customers = session.readS3File(
"sales_s3", "acme-retail-data", "raw/customers.csv", fileType="csv"
)
session.register("orders", orders)
session.register("customers", customers)
top = session.query(
"""
SELECT c.segment, count(*) AS orders, round(sum(o.amount), 2) AS revenue
FROM orders o
JOIN customers c USING (customer_id)
GROUP BY c.segment
ORDER BY revenue DESC
""",
returnFormat="pandas",
)
print(top)register also accepts pandas DataFrames and Arrow tables, so you can mix
DuckDB with pandas code:
import pandas as pd
from GZ.DuckDBUtils import duckSession
session = duckSession()
rates = pd.DataFrame({"region": ["EMEA", "APAC"], "fx": [1.08, 0.65]})
session.register("rates", rates)
print(session.query("SELECT * FROM rates ORDER BY region", returnFormat="pandas"))Query the Groundzero Lakehouse#
The Groundzero Lakehouse is an Apache Iceberg lakehouse. From the DuckDB runtime you read it through the lakehouse catalog. Table-level permissions, column masking and row policies are applied for the user running the code.
Read only
Lakehouse access from DuckDB is read only. writeGzLakehouse raises
PermissionError. To write lakehouse tables, use the Spark runtime.
Read a table or run SQL#
from GZ.DuckDBUtils import duckSession
session = duckSession(siteName="acme")
# Whole table; the name is database.table
orders = session.readGzLakehouse(
connName="lakehouse_main",
tableName="retail.orders",
)
# SQL: always qualify tables as database.table
top = session.readGzLakehouse(
connName="lakehouse_main",
query="""
SELECT region, sum(amount) AS revenue
FROM retail.orders
WHERE ordered_at >= DATE '2026-09-01'
GROUP BY region
""",
returnFormat="pandas",
)Rules the runtime enforces:
- Provide
tableNameorquery. If you give neither, the call fails withEither 'query' or 'tableName' must be provided. - Only read-only statements run (
SELECT,SHOW,DESCRIBE,EXPLAIN). Anything else fails withOnly read-.only queries are allowed - Table references in a query must be fully qualified. An unqualified table
raises
Use fully qualified table names. - A connection that points at an external lakehouse needs a site name: pass
siteNametoduckSession()(one site for all lakehouse connections) orsiteNames={"lakehouse_for a mapping, or passmain": "acme"} siteNametoreadGzLakehouse. One session can use only one site per connection; to use another site, create a new session.
Filters from the UI#
readGzLakehouse accepts structured filters that are added to the query as
extra predicates, which keeps the query text stable while values change:
sales = session.readGzLakehouse(
connName="lakehouse_main",
query="SELECT * FROM retail.orders",
filters=[
{"column": "region", "op": "in", "values": ["EMEA", "APAC"]},
{"column": "amount", "op": "gte", "values": [100]},
],
)Supported operators are in, eq, between, gte, gt, lte and lt. A
malformed filter raises an error; the query never runs unfiltered.
Keep a lakehouse table in the session#
registerLakehouseTable reads a table once and keeps it for repeated queries.
The table is named lakehouse_<alias>:
session.registerLakehouseTable(
connName="lakehouse_main",
tableName="retail.customers",
alias="customers",
)
vip = session.query(
"SELECT * FROM lakehouse_customers WHERE segment = 'vip' LIMIT 10"
)By default the table is materialized as a physical DuckDB table. Pass
materialize=False to register it as a view over the Arrow data instead.
Time travel and snapshots#
Groundzero Lakehouse tables are Iceberg tables. Use DuckDB's Iceberg syntax in
your query where the extension supports it.
Write results#
DuckDB writes with COPY, so results stream to the destination without
materializing in Python.
from GZ.DuckDBUtils import duckSession
session = duckSession()
session.readS3File(
"sales_s3", "acme-retail-data", "raw/orders/2026-09-30.parquet",
targetDuckdbTable="orders",
)
session.query("""
CREATE TABLE summary AS
SELECT region, count(*) AS orders FROM orders GROUP BY region
""")
# Write a DuckDB table
session.writeS3File(
connName="sales_s3",
bucketName="acme-retail-data",
filePath="curated/summary.parquet",
fileType="parquet",
sourceTable="summary",
)
# Write a query result as CSV with options
session.writeS3File(
connName="sales_s3",
s3FullUrl="s3://acme-retail-data/curated/summary.csv",
fileType="csv",
sourceQuery="SELECT * FROM summary ORDER BY region",
writeOptions={"header": True},
)For databases use writeJdbc(connName, targetTable, data=None, sourceTable=None,
sourceQuery=None, mode="append"), where mode is append or replace:
session.writeJdbc(
connName="orders_pg",
targetTable="reporting.region_summary",
sourceTable="summary",
mode="replace",
)Most other connectors have a matching write... method; see the connector
table in the API reference. Supported file types for writeS3File,
writeGcs and writeAzureBlob are parquet, csv and json; any other
value raises Unsupported file type.
Return output and previews#
When code runs as a dataset (or any run that returns rows), Groundzero looks for output in two places, in this order of priority:
- a value passed to
gz_output(value); if called more than once, the last value wins; - a variable named
outputDF.
If both exist, gz_output() is used and a warning is logged.
The accepted types and what happens to them:
| Type | Handling |
|---|---|
| DuckDB relation | Limited to 100,000 rows, converted through Arrow |
pyarrow.Table, RecordBatch, RecordBatchReader |
Sliced to 100,000 rows |
| pandas DataFrame | head(100000); datetimes become YYYY-MM-DD HH:MM:SS strings, numeric NaN becomes "NaN" |
| list | First 100,000 items; dict items become rows |
Any other type fails with outputDF must be DuckDBPyRelation, pa..
The schema returned with the rows uses these type names: integer, long,
short, byte, string, boolean, double, float, date, timestamp,
time, binary, decimal, interval, array, json and null.
Previews and dashboards page through the result: the response carries
totalRecords, totalPages, pageNumber, hasMore and the data for the
requested page. Asking for a page past the end fails with Page N is out of
range. Total pages: X for page size Y.
Identical code returns cached rows
Dataset output is cached by the exact text of your code. Re-running unchanged code returns the cached rows, without reading the source again, for up to 15 minutes. Results that read governed lakehouse tables are cached per user policy. Change the code (for example a comment) or wait for the cache to expire to force a refresh.
from GZ.DuckDBUtils import duckSession
session = duckSession()
orders = session.readS3File(
"sales_s3", "acme-retail-data", "raw/orders/2026-09-30.parquet"
)
session.register("orders", orders)
# Either of these returns rows; do not use both.
gz_output(session.query("SELECT region, count(*) AS n FROM orders GROUP BY 1"))Use parameters and placeholders#
Groundzero substitutes values into your code text before it runs. There are two kinds.
Runtime placeholders#
These describe the run and are available in every runtime. Write them as
${NAME} or {NAME}.
| Placeholder | Value |
|---|---|
STRTTM |
Run start time |
ENDTM |
Time the placeholder is evaluated |
CLNTNM |
Client name |
SITENM |
Site name |
PRJNM |
Project name |
JOBNM |
Job name |
RTE |
Runtime name |
RGN |
Region |
USR |
User running the code |
USRGRPS |
The user's groups, comma separated, each quoted |
Each placeholder expands to a Python string literal that already contains single
quotes, so it can be dropped straight into SQL text. For a project named
Sales, the line
project = ${PRJNM}becomes project = "'Sales'", a string whose value is 'Sales' including the
quotes. Use it like this:
audit = session.query(f"SELECT * FROM audit WHERE project = {project}")Brace names are replaced everywhere
{PRJNM} is replaced even inside an f-string or a SQL snippet, and the
placeholder names are case sensitive. Do not name your own variables with
these upper-case names.
Job parameters#
When you start a job through the external job API you can pass your own
parameters as placeholders. Each key is $ followed by a name made of letters,
digits and underscores. Values may be a string, number, boolean, null or a list
of those. Every $NAME in the job's code is replaced by the matching Python
literal before the run:
cutoff = $CUTOFF_DATE
regions = $REGIONS
orders = session.query(
f"SELECT * FROM orders WHERE ordered_at >= DATE '{cutoff}'"
)Request body (POST to the external job endpoint):
{
"projectName": "Retail Analytics",
"jobName": "daily_orders",
"rteName": "duckdb",
"computeName": "Medium",
"placeholders": {
"$CUTOFF_DATE": "2026-09-01",
"$REGIONS": ["EMEA", "APAC"]
}
}Placeholder names that are not valid or values of unsupported types are rejected
before anything runs (Invalid placeholder name: ., Invalid value for
placeholder: .).
Run jobs and schedule them#
An ETL job is a Python file saved in a project. To run it:
- Open the job in the ETL job editor and choose the runtime and compute in the toolbar (see the Quickstart).
- Run it once from the editor to check the output pane and logs.
- Open the scheduler, pick the project and job, and set:
- Schedule type:
BatchorStreaming. A batch schedule adds a recurrence (cron-style) and an Ends choice ofNeverorOna date and time. - RTE: the runtime and compute to use (both are required).
- Name and Description.
- Schedule type:
When a schedule has an end time, the run stops at that time. A job ends when your code finishes.
To chain jobs, call executeJob from a parent job. It runs the named sub-jobs of
the current multi-job run in order and returns their results:
from GZ.JobUtils import executeJob
results = executeJob(["load_orders", "build_summary"])executeJob raises ValueError if none of the names match a sub-job of the
current multi-job run.
Use extra packages#
Use this when your code needs a library the runtime does not include. You have three options, from lightest to heaviest.
- An ML variant: choose the DuckDB scikit-learn, PyTorch or TensorFlow runtime when the library you need is listed there (see Machine-learning variants).
-
A custom runtime: administrators can build a runtime from any base runtime plus your own
requirements.txt. Open Custom RTE in the admin area and choose Add custom RTE:- Base Image: pick the runtime to extend, for example the DuckDB scikit-learn runtime.
- Name: a short name. The runtime kind is added as a prefix, so a name
of
forecastingon a DuckDB runtime is shown asduckdb-forecasting. - Choose File: a
.txtfile inrequirements.txtformat.
The page lists each custom runtime with its creator, creation time and status. The build can take a while, and the status changes when it finishes. Once it succeeds, choose the new runtime like any other.
-
Install in a notebook:
pip installworks for the current session. Packages installed this way last only until you stop the session, so move them to a custom runtime for jobs.
To check a package is available, import it in a notebook cell.
Leave the pinned packages alone
The runtime pins NumPy, pandas, scikit-learn and DuckDB. A custom
requirements.txt that upgrades them can break the GZ library, so add new
packages and leave those alone.
Work with files#
Your code can use local scratch space. The sandbox allows reading and writing
under /tmp, /home/workspace and /home, and rejects other locations:
import pandas as pd
df = session.query("SELECT 1 AS a, 2 AS b", returnFormat="pandas")
df.to_csv("/tmp/scratch.csv", index=False)
back = session.query("SELECT * FROM read_csv('/tmp/scratch.csv')")Files written locally disappear when the run ends. Write anything you want to keep to an object store or database connection.
Job and dataset code runs with restrictions. Modules that give network or process
access (socket, urllib, http and others) cannot be imported, subprocess is
blocked, eval, exec and compile are not allowed, and secret values in
os.environ read as ****. Use connections for network access.
Tune performance#
DuckDB is fast by default. These are the levers that matter.
- Select columns and filter early. Parquet is columnar and DuckDB reads only
the columns and row groups a query needs. Prefer
SELECT col_a, col_bandWHEREclauses toSELECT *. - Stay lazy. Relations and SQL do not copy data into Python. Calling
.df()orreturnFormat="pandas"on a large table pulls it into memory. - Read many files with a glob.
s3FullUrl="s3:lets DuckDB parallelize across files. Pass/ / bucket/ path/ *. parquet" readOptions={"hive_for partitioned layouts.partitioning": True} - Aggregate before returning. A dataset returns at most 100,000 rows; do the grouping in SQL.
- Right-size the compute. The DuckDB memory limit is 80 percent of the
compute's memory. When a query needs more it spills to disk under
/tmp/duckdb-spill, which is slower. If a run is slow and logs show spilling, choose a larger compute. - Control threads and memory per session when several heavy queries share a
run:
duckSession(threads=4, memory_.limit="6GB") - Convert to Arrow, not pandas.
relation.is zero-copy friendly and works with Parquet writers and Polars.to_ arrow_ table() - Materialize reused data. If a relation is queried many times, create a
table once with
CREATE TABLE x AS ...(ortargetDuckdbTable) so DuckDB does not re-read the source for every query.
from GZ.DuckDBUtils import duckSession
session = duckSession(threads=2, memory_limit="1GB")
# Materialize once, query many times
session.readS3File(
"sales_s3", s3FullUrl="s3://acme-retail-data/raw/orders/*.parquet",
targetDuckdbTable="orders_remote",
)
session.query("""
CREATE TABLE orders_local AS
SELECT order_id, region, amount FROM orders_remote
""")
print(session.query("SELECT region, avg(amount) AS avg_amount "
"FROM orders_local GROUP BY region ORDER BY 1",
returnFormat="pandas"))
print(session.query("SELECT current_setting('threads') AS threads",
returnFormat="pandas"))Log and debug#
Anything your code prints is captured and shown in the job's log view with the
job identifier prefix. The standard logging module writes to the same stream.
Very long lines (over 200,000 characters) are split into numbered
LARGE_ chunks so the UI can reassemble them.
When your code raises an exception, the run fails and the error is reduced to the line in your code that raised it, for example:
ValueError: Either s3FullUrl or both bucketName and filePath must be provided at line 7For syntax errors the message ends with the offending line number. Use
print(session. to inspect query
plans and session.listTables() to see what is registered.
To raise the verbosity of the helper library, pass logLevel="DEBUG" to
duckSession.
Handle secrets#
Never put keys or passwords in code. Create a connection in Groundzero and refer
to it by name. Groundzero supplies the credentials to the helper library, and your
code never sees them. In jobs and datasets, os.environ shows secret values as
****. Reading Groundzero's own lakehouse storage buckets (names starting with
gz-lakehouse-) directly is refused with
Direct access to gz-.
If you need a native client for a connection, ask the helper library for one:
from GZ.Client import getClient
s3 = getClient().getS3Client("sales_s3")
resp = s3.list_objects_v2(Bucket="acme-retail-data", Prefix="raw/", MaxKeys=5)Extract text from PDFs#
parsePDF and parsePDFCorpus extract text and tables from PDFs (Docling with
RapidOCR) and write results to S3.
result = session.parsePDFCorpus(
s3ConnName="sales_s3",
sourcePrefix="incoming/contracts/",
outputPrefix="parsed/contracts",
pageRangeSize=64,
)
print(result["status"], result["documentCount"], result["manifestUri"])To check it worked, result["status"] reports the outcome and manifestUri points
to the manifest of parsed documents.
Discovery is recursive and case insensitive. Results are restartable: running again with the same source and output skips page ranges that were already committed. OCR processes one document model at a time, so throughput is bounded by that. For distributed OCR over very large corpora use the Spark runtime.
Run Groundzero Agents over documents#
invokeAgent calls an approved Groundzero Agent and waits for its result;
invokeAgentPDFCorpus runs an Agent over every document in an S3 prefix and
writes one result per document.
result = session.invokeAgentPDFCorpus(
connName="agents",
agentId="00000000-0000-4000-8000-000000000001",
message="List each policy's effective date and exceptions.",
pdfSourceConnName="sales_s3",
pdfSourcePrefix="incoming/policies/",
pdfSinkConnName="sales_s3",
pdfSinkPrefix="agent-results/policies",
summaryWorkers=4,
)
print(result["status"], result["resultsUri"])The corpus run resolves the approved Agent version and its response schema
before any OCR starts. With a JSON response schema configured the output mode is
structured; without one the Agent returns cited facts. summaryWorkers runs
between 1 and 32 documents concurrently (default 4), the document limit defaults
to 10,000 and the Agent-call budget to 50,000. Unchanged documents are skipped on
later runs.
Check data quality#
runDataQualityChecks, runTableDataQualityChecks and
runQueryDataQualityChecks run Qualipilot against a relation, a table or a
query using the session's own DuckDB connection, and can add an LLM-written
narrative through a Groundzero LLM connection:
report = session.runTableDataQualityChecks(
tableName="orders_local",
connectionName="llm_openai",
includeLlm=True,
)
session.saveDataQualityReport(report, "/tmp/orders_quality.html", "html")Set includeLlm=False to run only the deterministic checks.
from GZ.DuckDBUtils import duckSession
session = duckSession()
session.query("""
CREATE TABLE orders_local AS
SELECT range AS order_id, 'EMEA' AS region, range * 1.5 AS amount
FROM range(100)
""")
report = session.runTableDataQualityChecks(
tableName="orders_local",
includeLlm=False,
)
session.saveDataQualityReport(report, "/tmp/orders_quality.json")