Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install spanner-graph-schema-best-practices@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin spanner-graph-schema-best-practices v1.0.0 follows the Agent Plugins spec.
gh skills-hub install spanner-graph-schema-best-practices Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/spanner-graph-schema-best-practices/ Extract the ZIP to .github/skills/ in your repo. The folder name must match spanner-graph-schema-best-practices for Copilot to auto-discover it.
Skill Files (4)
SKILL.md 30.2 KB
---
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](references/attribution.md).
## 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):
1. **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](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt)).
If `gcloud` or the local emulator is unavailable, generate and review the
Spanner Graph DDL statically using the rules and reference templates below.
2. **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](https://cloud.google.com/spanner/pricing) and
[Google Cloud pricing](https://cloud.google.com/pricing)), and, after the
user confirms, enable the API:
```bash
gcloud services enable spanner.googleapis.com --project={project_id}
```
3. **Authentication**: Authenticate with `gcloud auth login` (interactive CLI),
`gcloud auth application-default login` (local SDKs), or
`GOOGLE_APPLICATION_CREDENTIALS` (service accounts).
4. **Required Identity and Access Management (IAM) Roles (Least Privilege)**:
- `roles/spanner.databaseReader` (or `roles/spanner.viewer`) to inspect DDL
via `gcloud spanner databases ddl describe`.
- `roles/spanner.databaseAdmin` to create databases or apply schema updates
(`gcloud spanner databases ddl update`).
5. **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](https://docs.cloud.google.com/spanner/docs/instance-configurations.md.txt)
and [Cloud locations](https://cloud.google.com/about/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](references/topology-and-edge-folding.md) (for
Steps 1–2) and
[Edge Traversal & Indexing](references/edge-traversal-and-indexing.md) (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](https://docs.cloud.google.com/spanner/docs/graph/best-practices-designing-schema.md.txt)
alongside [Topology & Edge Folding](references/topology-and-edge-folding.md)
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](references/topology-and-edge-folding.md) for full
multi-table DDL examples and apply these rules:
1. **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`):
```sql
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 `INT64` keys (bit-reversed sequence or random/hashed `INT64`) 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.
2. **Advanced — Co-Locate Strict 1:N Containment Child Node Tables
(`INTERLEAVE IN PARENT`)**:
- **Cardinality Guardrail — Strict `1:N` Containment 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 `IpNode`s—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:N` containment 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:
```sql
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) REFERENCES IpNode (ip_id)
-- DESTINATION KEY (ip_id, card_id) REFERENCES IpCard (ip_id, card_id))
```
- **Always Reference the Full Composite Key**: Because interleaving changes
the child node's primary key to `({parent_key}, {child_key})`, always
declare `KEY ({parent_key}, {child_key})` on the child node table and list
every key column in any `SOURCE KEY` or `DESTINATION KEY` referencing it.
Referencing only `{child_key}` against a 2-column `KEY` is accepted by
Spanner and silently matches every row sharing that partial key.
3. **Fold `many-to-{0,1}` and `many-to-1` Edges into the Source Node Table**:
- When each source node has **at most one** outgoing edge of a given type to
a target node (`many-to-{0,1}` or `many-to-1`, such as
`(IpNode)-[:ipOnOptical]->(OpticalNode)`), store the target key
(`optical_node_id`) as a column directly on the source node table and
project that table in both `NODE TABLES` (`IpNode`) and `EDGE TABLES`
(`IpNode AS IpOnOpticalEdge`). A `NULL` target key means the node has no
such edge (`many-to-0`):
```sql
CREATE TABLE IpNode (
ip_id STRING(64) NOT NULL,
optical_node_id STRING(64),
FOREIGN KEY (optical_node_id) REFERENCES OpticalNode (optical_node_id),
) PRIMARY KEY (ip_id);
-- In CREATE PROPERTY GRAPH:
-- EDGE TABLES (IpNode AS IpOnOpticalEdge
-- SOURCE KEY (ip_id) REFERENCES IpNode (ip_id)
-- DESTINATION KEY (optical_node_id) REFERENCES OpticalNode (optical_node_id)
-- LABEL ipOnOptical)
```
Folding removes a separate edge table to maintain and write. The query
speedup is modest and appears only when a query filters on or returns
source-node properties, because the node and its edge come from the same
row; key-only traversals perform the same as with an interleaved edge
table.
- **Enforce the Folded Foreign Key, Never `ON DELETE CASCADE`**: Declare the
target-key column as an enforced foreign key to the target node table so it
can't point to a missing node. `ON DELETE CASCADE` on this foreign key
would delete the source node rows, not just their edges; to delete a
target node, first set the referencing target keys to `NULL`. Use
`NOT ENFORCED` only for target node tables in datasets with high-degree hub
nodes, after confirming the trade-off with the user (see Step 3).
- **Cardinality Guardrail — Do Not Fold `M:N` Edges into Node Tables**: Never
fold a many-to-many (`M:N`) edge into a node table by adding `target_id` to
the node's primary key, because doing so duplicates the node row for every
connected target and corrupts node-level aggregations like
`MATCH (n:Node) RETURN COUNT(n)`. Keep `M:N` relationships in a dedicated
edge table interleaved in the source node table.
4. **Consolidate 1:1 Subtype Nodes & Fold 1:1 Intermediate Pass-Through Hops**:
- Merge fragmented 1:1 subtype tables (e.g., `RouterNode`, `SwitchNode`,
`FirewallNode` sharing the same entity key) into a unified node table (such
as `DeviceNode`) with a type discriminator column (such as `device_type`).
- If there is no need to model an intermediate pass-through node type in the
graph, fold 1:1 pass-through intermediate tables (such as a `CableNode`
table where each cable only connects two `Router` endpoints via
`Router <-[:terminatedBy]- CableNode -[:terminatedBy]-> Router`) directly
into a single edge table so each router-to-router step is 1 hop instead of
2. Doing so leaves the intermediate node type (`CableNode`) out of the
graph schema: its attributes become edge properties, it can no longer be
matched as a node (`MATCH (c:CableNode)`), and it cannot have edges of its
own. **Confirm with the user that this is desired before choosing this
model** (see Section 5.2 of
[Topology & Edge Folding](references/topology-and-edge-folding.md) for the
before-and-after comparison):
```sql
CREATE TABLE Router (
router_id STRING(64) NOT NULL,
site_name STRING(128),
) PRIMARY KEY (router_id);
-- Each cable becomes one edge row between its two routers.
CREATE TABLE CableLink (
router_id STRING(64) NOT NULL,
peer_router_id STRING(64) NOT NULL,
cable_id STRING(64) NOT NULL,
capacity_gbps INT64,
FOREIGN KEY (peer_router_id) REFERENCES Router (router_id),
) PRIMARY KEY (router_id, peer_router_id, cable_id),
INTERLEAVE IN PARENT Router ON DELETE CASCADE;
CREATE OR REPLACE PROPERTY GRAPH CableGraph
NODE TABLES (Router)
EDGE TABLES (
CableLink
SOURCE KEY (router_id) REFERENCES Router (router_id)
DESTINATION KEY (peer_router_id) REFERENCES Router (router_id)
LABEL cableLink PROPERTIES (cable_id, capacity_gbps)
);
-- One router-to-router hop: MATCH (a:Router)-[:cableLink]->(b:Router)
```
5. **Align Shared Label Properties and Graph-Wide Property Types**:
- When multiple node or edge tables share the same `LABEL`, expose the exact
same property names and SQL data types across every table declaring that
label. Moreover, across the **entire property graph** (even between
unrelated labels or between nodes and edges), any property with the same
exposed name must have the same SQL data type (`The property declaration of
'id' has type conflicts...`). Use column aliases or scalar SQL expressions
such as `CAST({col} AS {target_type}) AS {property_name}` in
`PROPERTIES (...)` when underlying column types differ.
### Step 3: Optimize Forward & Reverse Edge Traversals
Configure physical co-location, foreign keys, and covering indexes for all
remaining edge tables as detailed in
[Edge Traversal & Indexing](references/edge-traversal-and-indexing.md):
1. **Forward Traversal (`(src)-[e]->(dst)`)**:
- Interleave the edge table into the source node table (`INTERLEAVE IN PARENT
{source_node_table} ON DELETE CASCADE`) and add a `FOREIGN KEY
({dst_key_cols}) REFERENCES {dest_node_table} ({dst_key_cols})` on the
destination key so the Spanner query optimizer can prune the destination
node table scan when queries only need the destination key:
```sql
CREATE TABLE PersonOwnAccount (
person_id INT64 NOT NULL,
account_id INT64 NOT NULL,
create_time TIMESTAMP,
FOREIGN KEY (account_id) REFERENCES Account (id),
) PRIMARY KEY (person_id, account_id),
INTERLEAVE IN PARENT Person ON DELETE CASCADE;
```
- For target node tables in datasets with high-degree **hub / super nodes**
(where individual target nodes receive thousands or millions of concurrent
incoming edges), consider a table-level informational foreign key (`NOT
ENFORCED`, configured on the table's `FOREIGN KEY` constraint rather than
per individual node) to avoid write lock contention on hub rows during
concurrent edge inserts while preserving optimizer join elimination.
Confirm this trade-off with the user first: informational foreign keys
don't prevent dangling edges, and because the optimizer uses them by
default, queries can return results that don't match the data if an edge
points to a missing node. Keep the foreign key enforced when the user needs
strict referential integrity.
2. **Reverse (`(dst)<-[e]-(src)`) & Any-Direction (`(a)-[e]-(b)`) Traversal**:
- Create a **Remote Interleaved Index** keyed by
`({dst_key_cols}, {src_key_cols})` with a `STORING ({edge_properties})`
clause and `INTERLEAVE IN {dest_node_table}` (without the `PARENT`
keyword):
```sql
CREATE INDEX {edge_table}ByDst
ON {edge_table} ({dst_id}, {src_id})
STORING ({edge_prop_1}, {edge_prop_2}),
INTERLEAVE IN {dest_node_table};
```
- **Note on `INTERLEAVE IN PARENT` vs. `INTERLEAVE IN`**: While
`INTERLEAVE IN PARENT` on a child table requires exact column *name*,
type, and order matching, `INTERLEAVE IN {dest_node_table}` on a secondary
index (Remote Index) uses *positional type matching*—so `{dst_id}`
co-locates in `{dest_node_table}`'s split even when the column name
differs from `{dest_node_table}`'s primary key name.
- **Store Non-Key Edge Columns by Default**: Including `{src_id}` in the
index key and, by default, adding all non-key edge columns to the `STORING`
clause (matching the Spanner Graph UI modeler behavior) enables a 100%
index-only scan without back-joining to the base edge table. If the edge
table has many or wide columns, discuss with the user which frequently
accessed edge properties to keep in `STORING`.
- **Undirected Queries on Directed Edges (`-[e:Transfers]-{1,4}`)**: Keep
plain any-direction traversal backed by the reverse index above. Don't add
a second swapped-key reverse edge type in `CREATE PROPERTY GRAPH` for
performance: querying it as a label union
(`-[:Transfers|ReverseTransfer]->{1,3}`) forces Spanner to evaluate a union
across two edge types at every hop, which is slower than
`-[:Transfers]-{1,3}`.
- **Mutually Symmetric Relationships (`Friend`, `Peer`) Stored as Directed
Pairs**: When an application stores each symmetric relationship as two
directed rows (`(user_a, user_b)` and `(user_b, user_a)` in one
transaction) under `PRIMARY KEY (src_id, dst_id)`, always query with
directed `-[:Friend]->` so outgoing traversals seek a single primary-key
prefix (especially beneficial on high-degree nodes). Never query a
double-stored edge table with undirected `-[:Friend]-`: because both
`(A, B)` and `(B, A)` exist in the table, an undirected pattern matches
both rows and returns every neighbor twice (and full-scans the table if no
reverse index exists).
### Step 4: Add Property-Filtering Indexes & Prevent Dangling Edges
By default, initial schema creation only requires primary keys and
topology/reverse-traversal indexes (Steps 2–3); you do not need to index node or
edge properties up front. Add the property-filtering indexes in items 1–2 below
only when the user's queries filter (`WHERE` / `FILTER`) or sort (`ORDER BY ...
LIMIT k`) on specific non-key properties (see Section 3 of
[Edge Traversal & Indexing](references/edge-traversal-and-indexing.md)):
1. **Node Property Filtering Indexes**: Create secondary indexes on node
columns frequently used in `WHERE` / `FILTER` clauses. Use `WHERE {col} IS
NOT NULL` (NULL-filtered index) for sparse properties to save storage and
write overhead:
```sql
CREATE INDEX AccountByNickName ON Account (nick_name) STORING (is_blocked);
CREATE INDEX AccountByCloseTime ON Account (close_time) WHERE close_time IS NOT NULL;
```
2. **Edge Property Filtering & Per-Node Top-K Indexes**:
- For forward or reverse traversal with edge property filters, lead the index
with the traversal endpoint key followed by the filtered column, and
interleave into the endpoint node table.
- For per-node Top-K queries (`ORDER BY e.{ts} DESC LIMIT k` from an anchored
node) on high-degree nodes, index `({src_id}, {ts} DESC)` with `STORING` so
Spanner pushes `LIMIT k` directly into the index scan and reads only `k`
index rows instead of sorting the full adjacency list:
```sql
-- Forward filter on (src_id, create_time)
CREATE INDEX PersonOwnAccountByTime
ON PersonOwnAccount (person_id, create_time), INTERLEAVE IN Person;
-- Per-node Top-K by create_time DESC
CREATE INDEX AccountTransferByTimeDesc
ON AccountTransferAccount (src_id, create_time DESC) STORING (amount),
INTERLEAVE IN Account;
```
- Never list the edge table's primary key columns in `STORING`; they are
already part of every index and Spanner rejects the DDL.
3. **Referential Integrity & TTL (`ROW DELETION POLICY`)**:
- Prevent dangling edges (edges pointing to deleted nodes) using `INTERLEAVE
IN PARENT {source_node_table} ON DELETE CASCADE` and `FOREIGN KEY ... ON
DELETE CASCADE` on the destination node.
- **Same-Node-Type Edge Exception**: When an edge connects two nodes of the
**same** table (e.g., `Account -> Account` in `AccountTransferAccount`),
Spanner does not allow combining `INTERLEAVE IN PARENT Account ON DELETE
CASCADE` with a second `ON DELETE CASCADE` foreign key to `Account`. If
symmetric cascading deletes are required when either endpoint is deleted,
make the edge table standalone (not interleaved) with two enforced
`FOREIGN KEY ... REFERENCES Account (id) ON DELETE CASCADE` constraints.
- When adding a `ROW DELETION POLICY (OLDER_THAN({timestamp_col}, INTERVAL
{n} DAY))` to a node table, ensure all attached edge tables either cascade
deletes (`ON DELETE CASCADE`) or use informational foreign keys (`NOT
ENFORCED`, which leaves dangling edges for the application to clean up),
because Spanner rejects node TTL policies if enforced non-cascading child
edges block expiration.
### Step 5: Validate Schema DDL & Tear Down Temporary Resources
Validate the generated DDL against the real Spanner engine whenever possible
before presenting it as final:
1. **Preferred — Validate on a User-Confirmed Spanner Instance**: Ask the user
whether they have a Spanner instance (for example, a development or test
instance) where you may create a temporary, empty database, and confirm the
instance and database name before creating anything (creating a database
can incur costs). Apply the complete schema (tables, indexes, and `CREATE
PROPERTY GRAPH`) to that empty database:
```bash
gcloud spanner databases create {temp_database_id} \
--instance={instance_id} --project={project_id} \
--ddl-file={schema_file}
```
Never apply unvalidated DDL to an existing database that contains data.
2. **Fallback — Local Spanner Emulator**: If no Spanner instance is available,
follow the official
[Spanner Emulator guide](https://docs.cloud.google.com/spanner/docs/emulator.md.txt)
to start or connect to the local emulator (if it isn't installed, ask the
user before installing it). Create an isolated `gcloud` configuration
(`gcloud config configurations create emulator --no-activate`) and pass
`--configuration=emulator` on every validation command so DDL never reaches a
real instance, then apply the schema with `gcloud spanner databases create
{database_id} --instance={instance_id} --ddl-file={schema_file}
--configuration=emulator`. Because the emulator doesn't reproduce every
engine-specific validation, tell the user that emulator validation is a
best-effort check and recommend re-validating on a real instance before
production use. If neither `gcloud` nor the emulator is available, verify
the DDL statically against the checklist below.
3. If the compiler reports errors (such as mismatched shared label properties,
invalid key arity in `SOURCE KEY` / `DESTINATION KEY`, or conflicting
`ON DELETE CASCADE` constraints on same-type nodes), fix the DDL and re-run
until validation succeeds.
4. **Clean Up Temporary Validation Resources**: Delete the temporary validation
database when finished (`gcloud spanner databases delete {temp_database_id}
--instance={instance_id} --quiet`, adding `--configuration=emulator` for the
emulator; also delete any temporary emulator instance with `gcloud spanner
instances delete {instance_id} --quiet --configuration=emulator`) so the
user doesn't incur ongoing storage charges.
5. Run through the **Schema Verification Checklist** below before returning the
final DDL.
## Schema Verification Checklist
- [ ] **No Monotonic Primary Keys & Compact Key Types**: Node and standalone
edge primary keys avoid sequential timestamps or auto-incrementing
integers as the first key part (prefer random/bit-reversed `INT64` or
native `UUID` over `STRING(36)`).
- [ ] **Edge Key Prefix & Co-Location**: Dedicated `M:N` edge tables use
`PRIMARY KEY ({src_key}, {dst_key}, ...)` and `INTERLEAVE IN PARENT
{source_node_table}`.
- [ ] **Interleaved Child Nodes Are Strict 1:N**: Node tables interleaved in
another node table (`INTERLEAVE IN PARENT`) represent strict `1:N`
containment; `M:N` relationships between node types use a dedicated edge
table instead.
- [ ] **Folded Pass-Through Node Types Are User-Confirmed**: Any 1:1
intermediate node type folded into an edge table (and therefore absent
from the graph schema) was explicitly confirmed with the user.
- [ ] **Cardinality-Safe Edge Folding**: Only `many-to-{0,1}` and `many-to-1`
edges are folded into source node tables via `Table AS Edge`; all `M:N`
edges remain in separate edge tables so node row counts (`COUNT(n)`) are
never inflated, and folded target-key columns use enforced foreign keys
without `ON DELETE CASCADE`.
- [ ] **Reverse Traversal Index Coverage**: Every edge traversed in reverse
(`<-[e]-`) or any direction (`-[e]-`) has a secondary index on
`({dst_key}, {src_key})` with `STORING (...)` (and `INTERLEAVE IN
{dest_node_table}` when key prefixes align).
- [ ] **Destination Join Elimination**: Edge tables define foreign keys on
`DESTINATION KEY` columns (enforced by default; `NOT ENFORCED` only for
hub nodes after the user accepts the dangling-edge risk).
- [ ] **Shared Label Uniformity**: Any `LABEL` shared across multiple tables
exposes identical property names and data types (using `CAST` where
needed).
- [ ] **Dangling Edge & TTL Safety**: `ON DELETE CASCADE` and `ROW DELETION
POLICY` rules are consistent across parent nodes and attached edges.
## Reference Guides
- [Edge Traversal & Indexing](references/edge-traversal-and-indexing.md):
Complete DDL patterns for forward interleaving, destination foreign keys,
reverse covering `STORING` indexes, property-filtering indexes, same-node-type
cascades, and TTL policies.
- [Topology & Edge Folding](references/topology-and-edge-folding.md): Decision
matrix for schematized vs. schemaless graphs, multi-table label alignment, 1:N
node hierarchy interleaving, 1:1 subtype consolidation, and cardinality-safe
`many-to-{0,1}` / `many-to-1` edge folding.
- [Official Spanner Graph Schema Design Best Practices](https://docs.cloud.google.com/spanner/docs/graph/best-practices-designing-schema.md.txt):
Google Cloud documentation for Spanner Graph physical schema design.
If you need product information that's not found in these references, use the
`search_documents` tool of the Developer Knowledge MCP server.
attribution.md 1.9 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with this
skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:spanner-graph-schema-best-practices)" \
gcloud <command> [flags]
```
Do not use `gcloud config set` for this: it would persist beyond the current
task and mislabel unrelated usage.
- **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
server, include
`agent-skills/1.0 (skill:spanner-graph-schema-best-practices)` in the
`User-Agent` header. If a `User-Agent` header is already specified, append
this string to the end of it rather than overwriting existing `User-Agent`
data — the collection pipeline parses the `agent-skills/<version>` and
`skill:<name>` tokens, so any rewording breaks attribution:
```
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:spanner-graph-schema-best-practices)
```
- **Constraint for Generated Code**: The tracking prefix is strictly for
commands you execute directly in the terminal. Do NOT include this tracking
prefix in generated scripts, Terraform templates, or code provided to the
user for their own repositories.
- **User Opt-Out**: If the user asks to disable or remove tracking or
attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
and custom `User-Agent` suffix from all commands.
edge-traversal-and-indexing.md 12.1 KB
# Edge Traversal, Indexing, and Lifecycle Best Practices
## Table of Contents
- [1. Optimizing Forward Edge Traversal](#1-optimizing-forward-edge-traversal): Lines 12-77
- [2. Optimizing Reverse and Any-Direction Edge Traversal](#2-optimizing-reverse-and-any-direction-edge-traversal): Lines 81-149
- [3. Secondary Indexes for Node and Edge Property Filtering](#3-secondary-indexes-for-node-and-edge-property-filtering): Lines 153-205
- [4. Preventing Dangling Edges and Configuring TTL](#4-preventing-dangling-edges-and-configuring-ttl): Lines 209-280
---
## 1. Optimizing Forward Edge Traversal
Forward edge traversal follows outgoing edges from a source node to a
destination node:
```sql
GRAPH FinGraph
MATCH (p:Person {id: @person_id})-[o:Owns]->(a:Account)
RETURN a.id AS account_id;
```
Optimize both hops of forward traversal (source-to-edge and
edge-to-destination):
### 1.1 Source-to-Edge: Composite Primary Key & `INTERLEAVE IN PARENT`
Prefix the edge table's primary key with the source node's primary key and
interleave the edge table into the source node table. This physically co-locates
outgoing edge rows on the same storage split as their parent source node,
converting source-to-edge lookup into a local primary-key prefix seek.
### 1.2 Edge-to-Destination: Foreign Keys & Hub-Node Protection
Add a foreign key constraint from the edge's destination key column(s) to the
destination node table's primary key. When a query only references the
destination node's key (e.g., `RETURN a.id`), Spanner's query optimizer uses the
foreign key guarantee to eliminate the destination node table join entirely.
- **Standard Nodes (Enforced Foreign Key, the Default)**: Prevents dangling
edges at write time and enables destination join elimination.
- **Target Node Tables in Datasets with High-Degree Hub / Super Nodes (`NOT
ENFORCED` Informational Foreign Key)**:
When a target node table contains hub nodes that receive high-concurrency edge
writes (e.g., a popular account, router, or tag with millions of incoming
edges), enforced foreign keys can cause read-write lock contention on those
destination rows. Adding `NOT ENFORCED` on the table's `FOREIGN KEY`
constraint (note: `NOT ENFORCED` is configured at the table level, not per
individual node row) avoids write-path lock contention while still enabling
optimizer join elimination, but it doesn't prevent dangling edges. Because
the optimizer uses informational foreign keys by default, queries can return
results that don't match the data if an edge points to a missing node.
Confirm with the user that the application can tolerate this before choosing
`NOT ENFORCED`; some customers require enforced foreign keys.
```sql
CREATE TABLE Person (
id INT64 NOT NULL,
name STRING(MAX),
) PRIMARY KEY (id);
CREATE TABLE Account (
id INT64 NOT NULL,
create_time TIMESTAMP,
close_time TIMESTAMP,
) PRIMARY KEY (id);
-- NOT ENFORCED is shown for an Account table with high-degree hub nodes, after
-- the user accepted the dangling-edge risk; omit it (the default) when strict
-- write-time referential integrity is required.
CREATE TABLE PersonOwnAccount (
id INT64 NOT NULL,
account_id INT64 NOT NULL,
create_time TIMESTAMP,
CONSTRAINT FK_Account FOREIGN KEY (account_id)
REFERENCES Account (id) NOT ENFORCED,
) PRIMARY KEY (id, account_id),
INTERLEAVE IN PARENT Person ON DELETE CASCADE;
```
---
## 2. Optimizing Reverse and Any-Direction Edge Traversal
Reverse edge traversal (`(dst)<-[e]-(src)`) and undirected/any-direction
traversal (`(a)-[e]-(b)`) cannot use an edge table's `(src_id, dst_id)` primary
key prefix directly:
```sql
GRAPH FinGraph
MATCH (a:Account {id: @account_id})<-[o:Owns]-(p:Person)
RETURN p.id AS person_id, o.create_time AS owned_since;
```
Without a reverse index, Spanner must perform a full table scan of the edge
table.
### 2.1 Covering Reverse Index with `STORING` and `INTERLEAVE IN`
Create a secondary index on the edge table keyed by the destination node key
(followed by the source node key), store all non-key edge columns in
`STORING (...)` by default (matching the Spanner Graph UI modeler behavior, or
discuss with the user which subset of frequently accessed edge columns to store
if the table has many wide columns), and interleave the index into the
destination node table when the destination key matches the destination node's
primary key:
```sql
CREATE INDEX AccountOwnedByPerson
ON PersonOwnAccount (account_id, id)
STORING (create_time),
INTERLEAVE IN Account;
```
Why each clause matters:
- **Key `(account_id, id)`**: Allows Spanner to seek directly on `account_id`
and obtain the source key `id` directly from the index key.
- **`STORING (create_time)`**: Makes the index covering for queries that project
or filter on `o.create_time`, avoiding a back-join (`ApplyJoin`) to the base
`PersonOwnAccount` table.
- **`INTERLEAVE IN Account` (Remote Interleaved Index)**: Physically co-locates
the reverse index entries in the same storage split as the destination
`Account` row. Unlike `INTERLEAVE IN PARENT` on base tables (which requires
exact column *name*, type, and order matching and enforces referential
integrity), `INTERLEAVE IN {dest_node_table}` on a secondary index uses
**positional type matching** (`account_id` matches `Account(id)` by data type
and key position without requiring identical column names). If the destination
node table is itself interleaved under a different parent whose key is not
present in the edge table, omit `INTERLEAVE IN` on the index and create a
global covering index `ON EdgeTable (dst_id, src_id) STORING (...)`.
### 2.2 Bidirectional Quantified Paths & `NOT NULL` Key Hygiene
1. **Declare All Primary Key and Endpoint Foreign Key Columns `NOT NULL`**:
- Always mark `id`, `src_id`, and `dst_id` columns as `NOT NULL`. This allows
the Spanner optimizer to eliminate null-handling branches across multi-hop
joins.
2. **Undirected Quantified Paths and Symmetric Relationships**:
- For deep undirected traversals (`-[e:Transfers]-{1,4}`), use plain
any-direction matching backed by the reverse index from Section 2.1. Don't
add a swapped-key reverse edge type for performance: querying it as a
label union (`-[:Transfers|ReverseTransfer]->{1,3}`) evaluates a union of
two edge types at every hop, which is slower than
`-[:Transfers]-{1,3}` for identical results.
- For inherently symmetric relationships (friend, peer, connected-to), store
both directions (insert X->Y and Y->X in the same transaction) and query
with directed `->` so outgoing traversals seek a single primary-key prefix.
This is faster than single storage plus a reverse index and `-[]-` on
high-degree start nodes, and about the same on low-degree nodes. Never
query doubled edges with `-[]-`: every neighbor is returned twice, and
without a reverse index on the doubled table the traversal full-scans it.
---
## 3. Secondary Indexes for Node and Edge Property Filtering
### 3.1 Filtering Nodes by Non-Key Properties
When queries filter nodes by non-key properties (such as `nick_name`, `status`,
or `site_name`), create a secondary index on the filtered column(s) and include
frequently projected properties in `STORING`:
```sql
CREATE TABLE Account (
id INT64 NOT NULL,
create_time TIMESTAMP,
close_time TIMESTAMP,
is_blocked BOOL,
nick_name STRING(MAX),
) PRIMARY KEY (id);
-- Standard property filter index
CREATE INDEX AccountByNickName
ON Account (nick_name)
STORING (is_blocked);
-- NULL-filtered index for sparse properties (saves storage and write I/O)
CREATE INDEX AccountByCloseTime
ON Account (close_time)
WHERE close_time IS NOT NULL;
```
### 3.2 Filtering and Ordering Edges by Properties During Traversal
When queries filter edges by a property (such as `create_time >= @min_time` or
`status = 'ACTIVE'`) or fetch the Top-K edges per node (`ORDER BY e.create_time
DESC LIMIT k`) while traversing from an anchored node, create a composite index
starting with the traversal endpoint key followed by the filtered or ordered
edge property:
Direction / Pattern | Query Pattern | Recommended Index DDL
--- | --- | ---
**Forward Filter** | `(p:Person {id: @id})-[o:Owns WHERE o.create_time >= @t]->(a:Account)` | `CREATE INDEX PersonOwnAccountByTime ON PersonOwnAccount (id, create_time), INTERLEAVE IN Person;`
**Reverse Filter** | `(a:Account {id: @id})<-[o:Owns WHERE o.create_time >= @t]-(p:Person)` | `CREATE INDEX AccountOwnedByPersonByTime ON PersonOwnAccount (account_id, create_time), INTERLEAVE IN Account;`
**Forward Top-K (`ORDER BY ... DESC LIMIT k`)** | `(a:Account {id: @id})-[t:Transfers]->(b:Account) RETURN b.id, t.amount ORDER BY t.create_time DESC LIMIT 10` | `CREATE INDEX AccountTransferByTimeDesc ON AccountTransferAccount (id, create_time DESC) STORING (amount), INTERLEAVE IN Account;`
For high-degree hub nodes, the **Forward Top-K** index changes the execution
plan from a `Sort Limit` over the full adjacency list to a `Limit` directly over
`IndexScan`, so the query reads only `k` index rows instead of every edge of
the hub.
> [!IMPORTANT]
> Never list primary key columns of the indexed table in `STORING`. Every index
> already carries the table's primary key columns (`id` and `account_id` here),
> and Spanner rejects the DDL: `Index AccountOwnedByPersonByTime specifies
> stored column id which is a key of table PersonOwnAccount`. Only `STORING`
> non-key columns.
---
## 4. Preventing Dangling Edges and Configuring TTL
A *dangling edge* (an edge whose source or destination node no longer exists)
degrades query performance and violates graph integrity.
### 4.1 Edges Connecting Different Node Types (`Person -> Account`)
Combine `INTERLEAVE IN PARENT ... ON DELETE CASCADE` (for the source node) with
an enforced `FOREIGN KEY ... ON DELETE CASCADE` (for the destination node):
```sql
CREATE TABLE PersonOwnAccount (
id INT64 NOT NULL,
account_id INT64 NOT NULL,
create_time TIMESTAMP,
CONSTRAINT FK_Account FOREIGN KEY (account_id)
REFERENCES Account (id) ON DELETE CASCADE,
) PRIMARY KEY (id, account_id),
INTERLEAVE IN PARENT Person ON DELETE CASCADE;
```
### 4.2 Edges Connecting the Same Node Type (`Account -> Account`)
When an edge connects two nodes of the **same** table (such as transfers
between two `Account` rows), Spanner does not permit combining `INTERLEAVE IN
PARENT Account ON DELETE CASCADE` with a second `FOREIGN KEY ... REFERENCES
Account ON DELETE CASCADE` on the same table. Choose based on your deletion
requirements:
- **Option A — Strict Bidirectional Delete Cascade (No Dangling Edges)**: Do
**not** interleave the edge table into `Account`. Instead, define two enforced
foreign keys with `ON DELETE CASCADE` on both `id` and `to_id`:
```sql
CREATE TABLE AccountTransferAccount (
id INT64 NOT NULL,
to_id INT64 NOT NULL,
amount FLOAT64,
create_time TIMESTAMP NOT NULL,
CONSTRAINT FK_FromAccount FOREIGN KEY (id)
REFERENCES Account (id) ON DELETE CASCADE,
CONSTRAINT FK_ToAccount FOREIGN KEY (to_id)
REFERENCES Account (id) ON DELETE CASCADE,
) PRIMARY KEY (id, to_id, create_time);
```
- **Option B — Maximum Forward Traversal Locality (Application-Managed Target
Cleanup)**: Interleave `AccountTransferAccount` into `Account` (`INTERLEAVE IN
PARENT Account ON DELETE CASCADE`) and use an informational foreign key (`NOT
ENFORCED`) on `to_id`, cleaning up incoming edges in application logic or via
TTL before deleting target accounts.
### 4.3 Time-to-Live (`ROW DELETION POLICY`) on Nodes and Edges
When configuring `ROW DELETION POLICY` on a node table, configure attached edge
tables so expired nodes can be garbage-collected without foreign-key violations:
```sql
CREATE TABLE Account (
id INT64 NOT NULL,
create_time TIMESTAMP,
close_time TIMESTAMP,
) PRIMARY KEY (id),
ROW DELETION POLICY (OLDER_THAN(close_time, INTERVAL 90 DAY));
CREATE TABLE AccountTransferAccount (
id INT64 NOT NULL,
to_id INT64 NOT NULL,
amount FLOAT64,
create_time TIMESTAMP NOT NULL,
) PRIMARY KEY (id, to_id, create_time),
INTERLEAVE IN PARENT Account ON DELETE CASCADE,
ROW DELETION POLICY (OLDER_THAN(create_time, INTERVAL 3650 DAY));
```
topology-and-edge-folding.md 20.2 KB
# Advanced Graph Topology & Edge Folding Best Practices
## Table of Contents
- [1. Schematized vs. Schemaless (`DYNAMIC LABEL`) Decision Matrix](#1-schematized-vs-schemaless-dynamic-label-decision-matrix):
Lines 18-121
- [2. Multi-Table Label Sharing & Property Alignment](#2-multi-table-label-sharing-property-alignment):
Lines 125-158
- [3. Co-Locating 1:N Node Hierarchies (`INTERLEAVE IN PARENT`)](#3-co-locating-1n-node-hierarchies-interleave-in-parent):
Lines 162-270
- [4. Folding `many-to-{0,1}` and `many-to-1` Edges into Node Tables](#4-folding-many-to-01-and-many-to-1-edges-into-node-tables):
Lines 274-379
- [5. Consolidating 1:1 Subtype Nodes & Folding 1:1 Intermediate Hops](#5-consolidating-11-subtype-nodes-folding-11-intermediate-hops):
Lines 383-487
---
## 1. Schematized vs. Schemaless (`DYNAMIC LABEL`) Decision Matrix
Spanner Graph supports both strongly-typed schematized definitions and flexible
schemaless definitions (`DYNAMIC LABEL` and `DYNAMIC PROPERTIES`).
### When to Choose Schemaless Over Schematized
While both models perform similarly on single-type traversals, **schemaless
designs can be faster when queries use quantified path patterns (`{m, n}`) that
span multiple node or edge types**, because all node types share one table and
all edge types share another:
```sql
-- Traverses multiple edge labels (Transfer|Withdraw) and untyped intermediate
-- nodes across 1 to 3 hops:
GRAPH FinGraph
MATCH p = (:Account {id: 1})-[:Transfer|Withdraw]->{1, 3}(:Account)
RETURN TO_JSON(p) AS path_json;
```
- **Why Schemaless Helps on Multi-Type Quantified Paths**: In a schematized
design with separate tables per node/edge type, a quantified path spanning
multiple types must union and join across every candidate node and edge table
at each hop. A single-table schemaless design stores all nodes in one `Nodes`
table and all edges in one `Edges` table using `DYNAMIC LABEL`, so each hop
scans and joins a single node/edge table pair instead of many tables. The
same applies to polymorphic edges, where one edge label connects several
different node types:
```sql
CREATE TABLE GraphNodes (
id INT64 NOT NULL,
label STRING(MAX) NOT NULL,
first_seen TIMESTAMP,
properties JSON,
-- Dynamic label values must be stored in lowercase (see the note below).
CONSTRAINT GraphNodesLabelLowercase CHECK (label = LOWER(label)),
) PRIMARY KEY (id);
CREATE TABLE GraphEdges (
id INT64 NOT NULL,
to_id INT64 NOT NULL,
edge_id INT64 NOT NULL,
label STRING(MAX) NOT NULL,
created_at TIMESTAMP,
properties JSON,
CONSTRAINT GraphEdgesLabelLowercase CHECK (label = LOWER(label)),
) PRIMARY KEY (id, to_id, edge_id),
INTERLEAVE IN PARENT GraphNodes ON DELETE CASCADE;
-- Hybrid properties design: expose the columns that this workload frequently
-- filters or indexes on (here, first_seen and created_at) as typed static
-- properties through an explicit PROPERTIES list, and store evolving
-- attributes in the JSON column. Choose these columns per workload.
CREATE OR REPLACE PROPERTY GRAPH FlexibleGraph
NODE TABLES (
GraphNodes
KEY (id)
PROPERTIES (id, label, first_seen)
DYNAMIC LABEL (label)
DYNAMIC PROPERTIES (properties)
)
EDGE TABLES (
GraphEdges
KEY (id, to_id, edge_id)
SOURCE KEY (id) REFERENCES GraphNodes (id)
DESTINATION KEY (to_id) REFERENCES GraphNodes (id)
PROPERTIES (id, to_id, edge_id, label, created_at)
DYNAMIC LABEL (label)
DYNAMIC PROPERTIES (properties)
);
```
`PROPERTIES ALL COLUMNS EXCEPT (properties)` is an equivalent shorthand (used in
the Spanner documentation) that exposes every column except the `JSON` column.
Either form keeps the `JSON` column from being exposed twice, as a static
property and as dynamic properties.
- **Store dynamic label values in lowercase**: A row whose `label` column holds
an uppercase or mixed-case value (`'Account'`) silently gets no dynamic
label: `MATCH (n:Account)` skips it, and `LABELS(n)` returns only the table's
default label. Labels in queries are case-insensitive (`:Account` matches a
stored `'account'`). The `CHECK (label = LOWER(label))` constraints above
reject bad writes; normalize existing data with `LOWER(label)` before adding
them.
- **Confirm the Workload Before Choosing**: If the user hasn't already described
their schema and queries, ask these questions before recommending a design:
1. **How many node and edge types do you need to maintain?** With a large
number of types (for example, more than 50 node types and 150 edge types),
mapping each type to its own table becomes a maintenance burden; a
schemaless design stores all node types in one table and all edge types in
another.
2. **Do existing queries traverse multiple labels?** For example,
`-[:Transfer|Withdraw]->{1, 3}`, or label conjunctions and disjunctions in
traversals. If such queries expand a large number of intermediate paths
(for example, more than 10,000) and are latency-sensitive, consider a
schemaless design.
- **When to Keep Schematized (Default)**: If quantified paths only traverse a
single node type and a single edge type (e.g.,
`(:Person)-[:Owns]->(:Account)-[:Transfer]->{1, 3}(:Account)`), or if your
workload relies on native non-JSON column types and secondary indexes on
typed columns, use a **schematized** design.
---
## 2. Multi-Table Label Sharing & Property Alignment
When multiple physical tables share a common graph `LABEL` (for example,
`EquipmentPort` and `OpticalPort` both exposing `LABEL Port`), Spanner Graph
enforces strict signature uniformity across all tables declaring that label:
1. **Identical Property Set**: Every table declaring the shared label must
expose the exact same property names under that label.
2. **Identical Data Types (Including Graph-Wide Property Type Rule)**: Every
property with the same exposed name across the **entire property graph**—even
on unrelated labels or between node and edge tables—must have the exact same
SQL data type (`The property declaration of 'id' has type conflicts...`). If
underlying physical columns have different data types (e.g., `INT64` in one
table and `STRING(64)` in another), alias the column names or use scalar
SQL expressions such as `CAST` inside `PROPERTIES (...)` so the exposed
graph property type matches across all tables:
```sql
CREATE OR REPLACE PROPERTY GRAPH NetworkGraph
NODE TABLES (
EquipmentPort
KEY (equip_id, port_id)
LABEL Port PROPERTIES (
CAST(port_id AS STRING) AS port_identifier,
bandwidth_gbps
),
OpticalPort
KEY (optical_node_id, port_code)
LABEL Port PROPERTIES (
port_code AS port_identifier,
CAST(wavelength_gbps AS INT64) AS bandwidth_gbps
)
);
```
---
## 3. Co-Locating 1:N Node Hierarchies (`INTERLEAVE IN PARENT`)
> [!IMPORTANT]
> **Advanced technique: strict `1:N` containment only.** Interleave a node table
> under another node table only when each child node is owned by exactly one
> parent node and cannot exist without it (for example, each `IpCard` is
> physically installed in exactly one `IpNode`). If the relationship is
> many-to-many (`M:N`)—for example, an `IpCard` or `Vrf` that can be associated
> with multiple `IpNode`s—or the child is an independent entity that outlives
> its parent, **do not** make it an interleaved child: keep both node tables
> standalone and model the relationship as a dedicated edge table interleaved in
> the source node table. Confirm the cardinality with the user before applying
> this layout.
When a graph contains a strict `1:N` parent-child containment hierarchy between
two node types (for example, each `IpCard` belongs to one `IpNode`), model the
hierarchy using Spanner's physical table interleaving AND dual node/edge
projection. In this example, ports stay in their own table and reference their
card through a folded `many-to-1` foreign key (see
[Section 4](#4-folding-many-to-01-and-many-to-1-edges-into-node-tables)):
```sql
CREATE TABLE IpNode (
ip_id STRING(64) NOT NULL,
site_name STRING(128),
) PRIMARY KEY (ip_id);
CREATE TABLE IpCard (
ip_id STRING(64) NOT NULL,
card_id STRING(64) NOT NULL,
card_type STRING(64),
) PRIMARY KEY (ip_id, card_id),
INTERLEAVE IN PARENT IpNode ON DELETE CASCADE;
-- Assumes port_id is globally unique. If port IDs are only unique within a
-- card (for example, eth0 on every card), the primary key must also include
-- the card's key: (ip_id, card_id, port_id).
CREATE TABLE IpPort (
port_id STRING(64) NOT NULL,
ip_id STRING(64) NOT NULL,
card_id STRING(64) NOT NULL,
port_status STRING(32),
CONSTRAINT FK_IpPort_IpCard FOREIGN KEY (ip_id, card_id)
REFERENCES IpCard (ip_id, card_id),
) PRIMARY KEY (port_id);
```
Declare `IpCard` as both a **Node Table** and an **Edge Table** (the
parent-to-child edge), and declare `IpPort` the same way (the folded
card-to-port edge):
```sql
CREATE OR REPLACE PROPERTY GRAPH NetworkGraph
NODE TABLES (
IpNode KEY (ip_id),
IpCard KEY (ip_id, card_id),
IpPort KEY (port_id)
)
EDGE TABLES (
IpCard AS HasCard
KEY (ip_id, card_id)
SOURCE KEY (ip_id) REFERENCES IpNode (ip_id)
DESTINATION KEY (ip_id, card_id) REFERENCES IpCard (ip_id, card_id)
LABEL hasCard,
IpPort AS HasPort
KEY (port_id)
SOURCE KEY (ip_id, card_id) REFERENCES IpCard (ip_id, card_id)
DESTINATION KEY (port_id) REFERENCES IpPort (port_id)
LABEL hasPort
);
```
- No separate `HasCard` or `HasPort` junction tables are needed.
- Traversing `(n:IpNode)-[:hasCard]->(c:IpCard)` reads contiguous rows in the
same storage split, because each node's cards are stored next to it.
- **Reference the Full Composite Key**: Interleaving changes `IpCard`'s primary
key to `(ip_id, card_id)`. Always query and reference an interleaved child
node by its full composite `KEY (ip_id, card_id)` in `NODE TABLES`, `SOURCE
KEY`, and `DESTINATION KEY`; referencing only a partial key against a
multi-column node `KEY` is accepted by Spanner and silently duplicates edge
matches.
### 3.1 Advanced: Interleaving a Third Level (Use with Caution)
You can also interleave `IpPort` under `IpCard` so that a node, its cards, and
its ports are stored together:
```sql
CREATE TABLE IpPort (
ip_id STRING(64) NOT NULL,
card_id STRING(64) NOT NULL,
port_id STRING(64) NOT NULL,
port_status STRING(32),
) PRIMARY KEY (ip_id, card_id, port_id),
INTERLEAVE IN PARENT IpCard ON DELETE CASCADE;
```
This speeds up traversals across the whole node-card-port hierarchy, but each
port is now identified by a key that combines three tables,
`(ip_id, card_id, port_id)`:
- Every edge that starts or ends at a port (for example, port-to-port links)
must carry all three key columns for that endpoint, which widens edge tables
and their indexes.
- Moving a port to another card changes its primary key, so the port row and
every edge that references it must be deleted and re-inserted.
Confirm with the user that they accept these trade-offs before recommending a
third interleave level.
---
## 4. Folding `many-to-{0,1}` and `many-to-1` Edges into Node Tables
Separate physical edge tables are only necessary when an edge has **many-to-many
(`M:N`)** cardinality (or when an edge connects 1:N targets that cannot be
interleaved and carries multiple parallel edges between the same endpoints).
### 4.1 The Edge-Folding Optimization (`Table AS Node` + `Table AS Edge`)
Whenever a directed relationship `(Source)-[:REL]->(Target)` has
**`many-to-{0,1}`** or **`many-to-1`** cardinality (meaning each `Source` node
connects to **at most one** `Target` node for that relationship, or a `1:N`
relationship viewed from the `N` side), fold the edge directly into the
`Source` node table as a foreign-key column:
```sql
CREATE TABLE OpticalNode (
optical_node_id STRING(64) NOT NULL,
locality_name STRING(128),
) PRIMARY KEY (optical_node_id);
-- Each IpNode sits on at most ONE OpticalNode (many-to-{0,1} / many-to-1):
-- fold the target optical_node_id directly into IpNode instead of creating an
-- IpOnOptical edge table. A NULL optical_node_id means the IpNode sits on no
-- OpticalNode (many-to-0); Spanner doesn't check foreign keys on rows whose
-- referencing column is NULL.
CREATE TABLE IpNode (
ip_id STRING(64) NOT NULL,
site_name STRING(128),
optical_node_id STRING(64),
CONSTRAINT FK_IpNode_OpticalNode FOREIGN KEY (optical_node_id)
REFERENCES OpticalNode (optical_node_id),
) PRIMARY KEY (ip_id);
-- Create a covering index on the foreign key for reverse traversals
-- (OpticalNode)<-[:ipOnOptical]-(IpNode) and non-null forward scans.
-- NULL_FILTERED is required if you co-locate this index via
-- INTERLEAVE IN OpticalNode, because Spanner rejects non-NULL_FILTERED
-- interleaved indexes on nullable columns:
CREATE NULL_FILTERED INDEX IpNodeByOpticalNode
ON IpNode (optical_node_id, ip_id)
STORING (site_name),
INTERLEAVE IN OpticalNode;
```
- **Keep the Folded Foreign Key Enforced (Default)**: An enforced foreign key
guarantees that every non-`NULL` `optical_node_id` points to an existing
`OpticalNode`. Deleting an `OpticalNode` fails while any `IpNode` still
references it; set those `optical_node_id` values to `NULL` (or delete the
`IpNode` rows) first. Never add `ON DELETE CASCADE` to a folded-edge foreign
key: it deletes the source `IpNode` rows, not just their edges.
- **Confirm Before Using `NOT ENFORCED`**: An informational foreign key
(`REFERENCES OpticalNode (optical_node_id) NOT ENFORCED`) avoids write lock
contention when many concurrent writes reference the same high-degree
`OpticalNode`, but it doesn't prevent dangling edges. Because the query
optimizer uses informational foreign keys by default, queries can return
results that don't match the data if an `optical_node_id` points to a missing
node. Ask the user whether they accept that risk before choosing
`NOT ENFORCED`; some customers require enforced foreign keys.
Then project `IpNode` as **both** a node table and an edge table in `CREATE
PROPERTY GRAPH`:
```sql
CREATE OR REPLACE PROPERTY GRAPH NdtGraph
NODE TABLES (
OpticalNode
KEY (optical_node_id)
LABEL OpticalNode PROPERTIES (optical_node_id, locality_name),
IpNode
KEY (ip_id)
LABEL IpNode PROPERTIES (ip_id, site_name, optical_node_id)
)
EDGE TABLES (
IpNode AS IpOnOpticalEdge
KEY (ip_id)
SOURCE KEY (ip_id) REFERENCES IpNode (ip_id)
DESTINATION KEY (optical_node_id) REFERENCES OpticalNode (optical_node_id)
LABEL ipOnOptical PROPERTIES (site_name, optical_node_id)
);
```
**Performance Gain**: In `MATCH (ip:IpNode)-[:ipOnOptical]->(opt:OpticalNode)`,
both `ip` and the `ipOnOptical` edge come from the same `IpNode` row, so Spanner
does not join `IpNode` to a separate `IpOnOptical` edge table. Compared with a
separate edge table interleaved in the source table, the gain is modest and only
appears when the query filters on or returns source-node properties; key-only
traversals perform the same. Folding still removes a table to maintain and
write.
### 4.2 Critical Cardinality Guardrail: NEVER Fold `M:N` Edges into Node Tables
> [!CAUTION]
> **Only fold `many-to-{0,1}` or `many-to-1` edges into a source node table.**
> Never fold a `many-to-many` (`M:N`) edge (or the `1`-to-`many` direction where
> a single source node has multiple target IDs) into a node table.
- **Why**: A relational node table requires one row per unique node entity
(`PRIMARY KEY (node_id)`). If a node connects to multiple targets (`M:N`) and
you add `target_id` to the node table's primary key (`PRIMARY KEY (node_id,
target_id)`), the node row is **duplicated once per edge**.
- **Consequence**: Queries that count or aggregate nodes—such as
`MATCH (n:Node) RETURN COUNT(n)` or degree aggregations—will return the
**edge count** instead of the **node count**, producing silently wrong query
results.
- **Rule**: Keep all `M:N` edges in a dedicated edge table (`PRIMARY KEY
(src_id, dst_id, ...)`, `INTERLEAVE IN PARENT SourceNode`).
---
## 5. Consolidating 1:1 Subtype Nodes & Folding 1:1 Intermediate Hops
### 5.1 Consolidating Fragmented 1:1 Subtype Node Tables
Avoid splitting a single logical entity into multiple 1:1 subtype tables (for
example, a base `IpRouter` table plus separate `BorderRouter`, `ProviderEdge`,
and `ServiceEdge` tables joined 1:1 on `router_id`). Instead, consolidate them
into a single physical node table (such as `DeviceNode`) with a type
discriminator column (such as `device_role`) that queries filter on
(`MATCH (d:DeviceNode {device_role: 'BorderRouter'})`).
### 5.2 Folding 1:1 Intermediate Pass-Through Hops
In physical network, supply-chain, or financial schemas, relational models
often normalize binary links into intermediate node tables (e.g.,
`RouterA <-[:terminatedBy]- CableNode -[:terminatedBy]-> RouterB`, where each
`CableNode` only connects two endpoints). If queries routinely traverse from
endpoint to endpoint (`RouterA -> RouterB`), representing `CableNode` as an
intermediate node doubles the hop count of every path query (turning a 3-link
traversal into a 6-hop query).
> [!IMPORTANT]
> **Confirm with the user before folding.** Folding removes the intermediate
> node type from the graph schema entirely: `CableNode` attributes become
> properties of the `cableLink` edge, `MATCH (c:CableNode)` no longer works, and
> a cable can no longer be the endpoint of its own edges (for example,
> `(CableNode)-[:hasTicket]->(MaintenanceTicket)`). Only apply this pattern
> when there is no need to model the intermediate node type as a first-class
> node, and ask the user to confirm that before choosing it.
**Before**: each cable is a node, and each router-to-router hop takes two
`terminatedBy` edges:
```sql
CREATE TABLE Router (
router_id STRING(64) NOT NULL,
site_name STRING(128),
) PRIMARY KEY (router_id);
CREATE TABLE CableNode (
cable_id STRING(64) NOT NULL,
capacity_gbps INT64,
status STRING(32),
) PRIMARY KEY (cable_id);
-- Each cable has exactly two terminations: cable_end 'A' and cable_end 'B'.
CREATE TABLE CableTermination (
cable_id STRING(64) NOT NULL,
cable_end STRING(1) NOT NULL,
router_id STRING(64) NOT NULL,
CONSTRAINT FK_CableTermination_Router FOREIGN KEY (router_id)
REFERENCES Router (router_id),
) PRIMARY KEY (cable_id, cable_end),
INTERLEAVE IN PARENT CableNode ON DELETE CASCADE;
CREATE OR REPLACE PROPERTY GRAPH CableGraph
NODE TABLES (Router, CableNode)
EDGE TABLES (
CableTermination AS TerminatedBy
SOURCE KEY (cable_id) REFERENCES CableNode (cable_id)
DESTINATION KEY (router_id) REFERENCES Router (router_id)
LABEL terminatedBy
);
-- One router-to-router hop:
-- MATCH (a:Router)<-[:terminatedBy]-(:CableNode)-[:terminatedBy]->(b:Router)
```
**After**: fold each cable into a single edge that connects its two routers
directly, with the cable's attributes stored as edge properties:
```sql
CREATE TABLE CableLink (
router_id STRING(64) NOT NULL, -- cable end A (source)
peer_router_id STRING(64) NOT NULL, -- cable end B (destination)
cable_id STRING(64) NOT NULL,
capacity_gbps INT64,
status STRING(32),
CONSTRAINT FK_CableLink_PeerRouter FOREIGN KEY (peer_router_id)
REFERENCES Router (router_id),
) PRIMARY KEY (router_id, peer_router_id, cable_id),
INTERLEAVE IN PARENT Router ON DELETE CASCADE;
CREATE OR REPLACE PROPERTY GRAPH CableGraph
NODE TABLES (Router)
EDGE TABLES (
CableLink
SOURCE KEY (router_id) REFERENCES Router (router_id)
DESTINATION KEY (peer_router_id) REFERENCES Router (router_id)
LABEL cableLink PROPERTIES (cable_id, capacity_gbps, status)
);
-- One router-to-router hop:
-- MATCH (a:Router)-[l:cableLink]->(b:Router)
```
- Cables are physically bidirectional, so traverse `CableLink` in either
direction with `-[:cableLink]-`, backed by a reverse index on
`(peer_router_id, router_id)` (see
[Edge Traversal & Indexing](edge-traversal-and-indexing.md)).
- If you need to support both legacy and new label names during migration,
declare both labels on the same edge table (`LABEL IpLink PROPERTIES
(cable_id, capacity_gbps) LABEL CableLink PROPERTIES (cable_id,
capacity_gbps)`). Spanner Graph has no `SYNONYMS` clause; `LABEL IpLink
SYNONYMS (CableLink)` is a syntax error.
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE