spanner graph schema best practices
Designs, reviews, and optimizes physical table schemas, indexes, and graph topologies for Spanner Graph on Google Cloud. Use when creating a new Spanner Graph schema, selecting node and edge primary key types, optimizing forward, reverse, or per-node Top-K edge traversals, designing interleaved node or edge tables and covering indexes, configuring cascading deletes and row deletion policies (TTL), evaluating schematized versus schemaless dynamic label graphs, or folding 1:1 and N:1 edges into no
Documentation & Preview
--- name: spanner-graph-schema-best-practices metadata: version: "1.0.0" category: Databases description: >- Designs, reviews, and optimizes physical table schemas, indexes, and graph topologies for Spanner Graph on Google Cloud. Use when creating a new Spanner Graph schema, selecting node and edge primary key types, optimizing forward, reverse, or per-node Top-K edge traversals, designing interleaved node or edge tables and covering indexes, configuring cascading deletes and row deletion policies (TTL), evaluating schematized versus schemaless dynamic label graphs, or folding 1:1 and N:1 edges into node tables. Don't use for tuning GQL query syntax or execution plans without schema changes (use spanner-graph-query-tuning), or when creating a zero-change graph overlay on existing relational tables (use spanner-relational-to-graph).
---
Spanner Graph Schema Design & Topology Best Practices
Design and optimize physical table layouts, primary keys, secondary indexes, and graph topologies for Spanner Graph (CREATE PROPERTY GRAPH) to maximize performance.
Usage Attribution
MUST READ: Before executing any gcloud, REST API, or MCP command, you MUST read and follow the instructions in Usage Attribution.
Safety & Verification Rules
- Obtain Confirmation Before Mutating Remote Databases: Do not execute
gcloud spanner databases ddl update, create, or delete against a remote Spanner instance without explicit user confirmation, because DDL mutations on live databases can trigger long-running schema backfills or break production queries. Always validate candidate DDL on the local Spanner Emulator first or output the DDL commands for user approval.
- Obtain Confirmation Before Changing the Cloud Environment: Ask the user
before running gcloud services enable, changing the active project or billing account, or creating or deleting Spanner instances, because these commands change the user's Google Cloud environment and can incur costs.
- Inspect Live Catalog Read-Only: When reviewing an existing Spanner
database, export the schema with gcloud spanner databases ddl describe {database_id} --instance={instance_id} --project={project_id} rather than guessing column types or key orders.
Prerequisites & Cloud Environment Setup
Before running gcloud spanner or emulator commands, verify that the environment meets these Google Cloud requirements (see spanner-basics for general Spanner instance provisioning and MCP setup):
- Google Cloud SDK & Static DDL Fallback: Verify whether the CLI is
installed (do not install gcloud without explicit user permission; see Install the gcloud CLI). If gcloud or the local emulator is unavailable, generate and review the Spanner Graph DDL statically using the rules and reference templates below.
- Project, Billing & API Enablement: Configure the target project (`gcloud
config set project {project_id}`), ensure an active billing account is attached (required even when provisioning a free trial instance; see Spanner pricing and Google Cloud pricing), and, after the user confirms, enable the API:
gcloud services enable spanner.googleapis.com --project={project_id}- Authentication: Authenticate with
gcloud auth login(interactive CLI),
gcloud auth application-default login (local SDKs), or GOOGLE_APPLICATION_CREDENTIALS (service accounts).
- Required Identity and Access Management (IAM) Roles (Least Privilege):
roles/spanner.databaseReader(orroles/spanner.viewer) to inspect DDL
via gcloud spanner databases ddl describe.
roles/spanner.databaseAdminto create databases or apply schema updates
(gcloud spanner databases ddl update).
- Region & Instance Configuration: When creating a new instance, select a
supported regional or multi-region configuration such as regional-us-central1 (gcloud config set spanner/instance {instance_id}; see Instance configurations and Cloud locations).
Terminology Glossary
Use these canonical terms consistently when reasoning about and explaining Spanner Graph schemas:
Term | Definition
--- | ---
Node table | A physical Spanner table projected in NODE TABLES of CREATE PROPERTY GRAPH; each row is one node.
Edge table | A physical table (or a node table projected a second time under an alias) listed in EDGE TABLES; each row is one directed edge from SOURCE KEY to DESTINATION KEY.
Node type / Edge type | One node or edge table projection in the property graph, identified by its name or alias (for example, IpCard AS HasCard is an edge type).
Label | The query-time name attached to a node or edge type via LABEL (static) or DYNAMIC LABEL (schemaless). One type can declare multiple labels, and one label can be shared by multiple types.
Property | A column or scalar SQL expression (for example, CAST(...) or LOWER(...)) exposed on a node or edge type via PROPERTIES (...) or DYNAMIC PROPERTIES.
Folded edge | A many-to-{0,1} or many-to-1 edge stored as a foreign-key column on the source node table, projected via {node_table} AS {edge_type} instead of a separate edge table.
1:N containment child node | A node table interleaved in its parent node table (INTERLEAVE IN PARENT) because each child is owned by exactly one parent; it serves as both a node type and the parent-to-child edge type.
Remote interleaved index | A secondary index on an edge table co-located with the destination node table via INTERLEAVE IN {dest_node_table} (no PARENT keyword) to accelerate reverse traversal.
Hub / super node | A node with thousands or millions of incoming or outgoing edges.
Core Schema Design Workflow
Follow this 5-step workflow when designing a new Spanner Graph schema or optimizing an existing one.
MUST READ: Steps 1–4 below are abbreviated summaries that include only short structural DDL snippets. The complete decision rules, trade-offs, and full multi-table CREATE TABLE, CREATE INDEX, and CREATE PROPERTY GRAPH examples live in the reference guides; before recommending or generating DDL, read Topology & Edge Folding (for Steps 1–2) and Edge Traversal & Indexing (for Steps 3–4).
Step 1: Choose Schematized vs. Schemaless Data Management
Select the graph storage model based on schema stability and query patterns. Read the *Compare schema types* section of the official Spanner Graph schema design best practices alongside Topology & Edge Folding for the full decision matrix:
Option | Best For | Key Mechanism
--- | --- | ---
Schematized (Default) | Stable domain models, strong type enforcement, non-JSON native types (TIMESTAMP, INT64, NUMERIC), and single-type quantified paths | Separate typed node/edge tables with explicit LABEL and PROPERTIES (col1, col2) declarations
Schemaless (Hybrid Properties Design) | Many node or edge types that are impractical to maintain as separate tables, frequently evolving schemas, polymorphic edges that connect many different node types, or latency-sensitive quantified path queries (-{1, 3}->) that span multiple node or edge labels | Single node table and single edge table using DYNAMIC LABEL (label) and DYNAMIC PROPERTIES (properties), plus an explicit PROPERTIES (...) list that keeps any frequently filtered or indexed columns as typed static properties alongside the JSON payload
If the user hasn't already described their schema and workload, ask before choosing: how many node and edge types they need to maintain (for example, more than 50 node types and 150 edge types), and whether latency-sensitive queries traverse multiple labels (for example, -[:Transfer|Withdraw]->{1, 3}) across a large number of intermediate paths (for example, more than 10,000).
Store DYNAMIC LABEL values in lowercase and enforce it with CHECK (label = LOWER(label)). Rows with uppercase or mixed-case label values silently get no dynamic label and drop out of labeled MATCH patterns (query labels themselves are case-insensitive).
Step 2: Optimize Physical Primary Keys & Topology Restructuring
Before creating secondary indexes, optimize the physical table topology so common traversals execute as local primary-key prefix seeks instead of distributed joins. Read Topology & Edge Folding for full multi-table DDL examples and apply these rules:
- **Re-Key Standalone Edge Tables by
(src_id, dst_id, [edge_id]), Enforce
NOT NULL, and Prefer INT64 / Native UUID Keys**:
- Avoid using a synthetic
PRIMARY KEY (edge_id)as the leading key column
on an edge table, because outgoing traversals from a source node cannot seek on src_id and must scan the entire table or rely on a secondary index.
- Define
PRIMARY KEY ({src_key_cols}, {dst_key_cols}, [{uniquifier_col}]),
declare all primary key and endpoint foreign key columns NOT NULL (which eliminates null-check branches in execution plans), and interleave the edge table into the source node table (INTERLEAVE IN PARENT {source_node_table} ON DELETE CASCADE):
CREATE TABLE AccountTransfer (
src_id INT64 NOT NULL,
dst_id INT64 NOT NULL,
transfer_id INT64 NOT NULL,
) PRIMARY KEY (src_id, dst_id, transfer_id),
INTERLEAVE IN PARENT Account ON DELETE CASCADE;- Prefer
INT64keys (bit-reversed sequence or random/hashedINT64) for
node and edge keys on traversal-heavy graphs. If you need UUIDs, use the native UUID type rather than STRING(36): 36-byte string keys widen secondary indexes and make multi-hop joins slower and more CPU-intensive than 8-byte INT64 or 16-byte native UUID keys.
- **Advanced — Co-Locate Strict 1:N Containment Child Node Tables
(INTERLEAVE IN PARENT)**:
- Cardinality Guardrail — Strict
1:NContainment Only: Use this
advanced technique only when each child node is owned by exactly one parent node and cannot exist without it (strict 1:N physical containment, such as IpCard belonging to one IpNode, or Subnet belonging to one Vpc). If the relationship is many-to-many (M:N)—for example, an IpCard or Vrf that can connect to multiple IpNodes—or the child is an independent entity, never interleave the child node table under the other node table; keep both as standalone node tables and model the relationship as a dedicated edge table interleaved in the source node table (Step 2.1). Confirm the cardinality with the user before applying this layout.
- When strict
1:Ncontainment applies, prefix the child node's primary key
with the parent's primary key and declare INTERLEAVE IN PARENT {parent_node_table}. This co-locates parent and child nodes in the same storage split AND lets the child table serve directly as the parent-to-child edge type without a separate edge table:
CREATE TABLE IpCard (
ip_id STRING(64) NOT NULL,
card_id STRING(64) NOT NULL,
) PRIMARY KEY (ip_id, card_id),
INTERLEAVE IN PARENT IpNode ON DELETE CASCADE;
-- In CREATE PROPERTY GRAPH:
-- NODE TABLES (IpNode KEY (ip_id), IpCard KEY (ip_id, card_id))
-- EDGE TABLES (IpCard AS HasCard SOURCE KEY (ip_id)