{"data":{"slug":"github-google-skills-skills-cloud-spanner-graph-schema-best-practices-15b57aac4fc3","title":"Design and Optimize Spanner Graph Schemas","summary":"Design, review, and optimize physical table schemas, indexes, and graph topologies for Spanner Graph on Google Cloud. Use when creating a new schema, selecting primary key types, optimizing edge traversals, or configuring cascading deletes. Deliverables include schema definitions and index configurations for node and edge tables.","url":"https:\/\/skillshunter.net\/skills\/github-google-skills-skills-cloud-spanner-graph-schema-best-practices-15b57aac4fc3","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-google-skills-skills-cloud-spanner-graph-schema-best-practices-15b57aac4fc3","markdown_url":"https:\/\/skillshunter.net\/skills\/github-google-skills-skills-cloud-spanner-graph-schema-best-practices-15b57aac4fc3.md","download_url":"https:\/\/skillshunter.net\/skills\/github-google-skills-skills-cloud-spanner-graph-schema-best-practices-15b57aac4fc3\/download","category":{"slug":"data-research","name":"Data & Research"},"editor_note":"Before executing any `gcloud`, REST API, or MCP command, you MUST read and follow the instructions in [Usage Attribution](references\/attribution.md). Verify that the Google Cloud SDK is installed and the environment meets Google Cloud requirements, including project configuration, billing setup, and API enablement.","instructions":"---\nname: spanner-graph-schema-best-practices\nmetadata:\n  version: \"1.0.0\"\n  category: Databases\ndescription: >-\n  Designs, reviews, and optimizes physical table schemas, indexes, and graph\n  topologies for Spanner Graph on Google Cloud. Use when creating a new Spanner\n  Graph schema, selecting node and edge primary key types, optimizing forward,\n  reverse, or per-node Top-K edge traversals, designing interleaved node or edge\n  tables and covering indexes, configuring cascading deletes and row deletion\n  policies (TTL), evaluating schematized versus schemaless dynamic label graphs,\n  or folding 1:1 and N:1 edges into node tables. Don't use for tuning GQL query\n  syntax or execution plans without schema changes (use\n  spanner-graph-query-tuning), or when creating a zero-change graph overlay on\n  existing relational tables (use spanner-relational-to-graph).\n---\n\n# Spanner Graph Schema Design & Topology Best Practices\n\nDesign and optimize physical table layouts, primary keys, secondary indexes, and\ngraph topologies for **Spanner Graph** (`CREATE PROPERTY GRAPH`) to maximize\nperformance.\n\n## Usage Attribution\n\n**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you\nMUST read and follow the instructions in\n[Usage Attribution](references\/attribution.md).\n\n## Safety & Verification Rules\n\n- **Obtain Confirmation Before Mutating Remote Databases**: Do not execute\n  `gcloud spanner databases ddl update`, `create`, or `delete` against a remote\n  Spanner instance without explicit user confirmation, because DDL mutations on\n  live databases can trigger long-running schema backfills or break production\n  queries. Always validate candidate DDL on the local Spanner Emulator first or\n  output the DDL commands for user approval.\n- **Obtain Confirmation Before Changing the Cloud Environment**: Ask the user\n  before running `gcloud services enable`, changing the active project or\n  billing account, or creating or deleting Spanner instances, because these\n  commands change the user's Google Cloud environment and can incur costs.\n- **Inspect Live Catalog Read-Only**: When reviewing an existing Spanner\n  database, export the schema with `gcloud spanner databases ddl describe\n  {database_id} --instance={instance_id} --project={project_id}` rather than\n  guessing column types or key orders.\n\n## Prerequisites & Cloud Environment Setup\n\nBefore running `gcloud spanner` or emulator commands, verify that the\nenvironment meets these Google Cloud requirements (see `spanner-basics` for\ngeneral Spanner instance provisioning and MCP setup):\n\n1. **Google Cloud SDK & Static DDL Fallback**: Verify whether the CLI is\n   installed (do not install `gcloud` without explicit user permission; see\n   [Install the gcloud CLI](https:\/\/docs.cloud.google.com\/sdk\/docs\/install-sdk.md.txt)).\n   If `gcloud` or the local emulator is unavailable, generate and review the\n   Spanner Graph DDL statically using the rules and reference templates below.\n2. **Project, Billing & API Enablement**: Configure the target project (`gcloud\n   config set project {project_id}`), ensure an active billing account is\n   attached (required even when provisioning a free trial instance; see\n   [Spanner pricing](https:\/\/cloud.google.com\/spanner\/pricing) and\n   [Google Cloud pricing](https:\/\/cloud.google.com\/pricing)), and, after the\n   user confirms, enable the API:\n   ```bash\n   gcloud services enable spanner.googleapis.com --project={project_id}\n   ```\n3. **Authentication**: Authenticate with `gcloud auth login` (interactive CLI),\n   `gcloud auth application-default login` (local SDKs), or\n   `GOOGLE_APPLICATION_CREDENTIALS` (service accounts).\n4. **Required Identity and Access Management (IAM) Roles (Least Privilege)**:\n   - `roles\/spanner.databaseReader` (or `roles\/spanner.viewer`) to inspect DDL\n     via `gcloud spanner databases ddl describe`.\n   - `roles\/spanner.databaseAdmin` to create databases or apply schema updates\n     (`gcloud spanner databases ddl update`).\n5. **Region & Instance Configuration**: When creating a new instance, select a\n   supported regional or multi-region configuration such as\n   `regional-us-central1` (`gcloud config set spanner\/instance {instance_id}`;\n   see [Instance configurations](https:\/\/docs.cloud.google.com\/spanner\/docs\/instance-configurations.md.txt)\n   and [Cloud locations](https:\/\/cloud.google.com\/about\/locations)).\n\n## Terminology Glossary\n\nUse these canonical terms consistently when reasoning about and explaining\nSpanner Graph schemas:\n\nTerm | Definition\n--- | ---\n**Node table** | A physical Spanner table projected in `NODE TABLES` of `CREATE PROPERTY GRAPH`; each row is one node.\n**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`.\n**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).\n**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.\n**Property** | A column or scalar SQL expression (for example, `CAST(...)` or `LOWER(...)`) exposed on a node or edge type via `PROPERTIES (...)` or `DYNAMIC PROPERTIES`.\n**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.\n**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.\n**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.\n**Hub \/ super node** | A node with thousands or millions of incoming or outgoing edges.\n\n## Core Schema Design Workflow\n\nFollow this 5-step workflow when designing a new Spanner Graph schema or\noptimizing an existing one.\n\n**MUST READ**: Steps 1\u20134 below are abbreviated summaries that include only\nshort structural DDL snippets. The complete decision rules, trade-offs, and\nfull multi-table `CREATE TABLE`, `CREATE INDEX`, and `CREATE PROPERTY GRAPH`\nexamples live in the reference guides; before recommending or generating DDL,\nread [Topology & Edge Folding](references\/topology-and-edge-folding.md) (for\nSteps 1\u20132) and\n[Edge Traversal & Indexing](references\/edge-traversal-and-indexing.md) (for\nSteps 3\u20134).\n\n### Step 1: Choose Schematized vs. Schemaless Data Management\n\nSelect the graph storage model based on schema stability and query patterns.\nRead the *Compare schema types* section of the official\n[Spanner Graph schema design best practices](https:\/\/docs.cloud.google.com\/spanner\/docs\/graph\/best-practices-designing-schema.md.txt)\nalongside [Topology & Edge Folding](references\/topology-and-edge-folding.md)\nfor the full decision matrix:\n\nOption | Best For | Key Mechanism\n--- | --- | ---\n**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\n**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\n\nIf the user hasn't already described their schema and workload, ask before\nchoosing: how many node and edge types they need to maintain (for example, more\nthan 50 node types and 150 edge types), and whether latency-sensitive queries\ntraverse multiple labels (for example, `-[:Transfer|Withdraw]->{1, 3}`) across a\nlarge number of intermediate paths (for example, more than 10,000).\n\nStore `DYNAMIC LABEL` values in lowercase and enforce it with\n`CHECK (label = LOWER(label))`. Rows with uppercase or mixed-case label values\nsilently get no dynamic label and drop out of labeled `MATCH` patterns (query\nlabels themselves are case-insensitive).\n\n### Step 2: Optimize Physical Primary Keys & Topology Restructuring\n\nBefore creating secondary indexes, optimize the physical table topology so\ncommon traversals execute as local primary-key prefix seeks instead of\ndistributed joins. Read\n[Topology & Edge Folding](references\/topology-and-edge-folding.md) for full\nmulti-table DDL examples and apply these rules:\n\n1. **Re-Key Standalone Edge Tables by `(src_id, dst_id, [edge_id])`, Enforce\n   `NOT NULL`, and Prefer `INT64` \/ Native `UUID` Keys**:\n   - Avoid using a synthetic `PRIMARY KEY (edge_id)` as the leading key column\n     on an edge table, because outgoing traversals from a source node cannot\n     seek on `src_id` and must scan the entire table or rely on a secondary\n     index.\n   - Define `PRIMARY KEY ({src_key_cols}, {dst_key_cols}, [{uniquifier_col}])`,\n     declare all primary key and endpoint foreign key columns `NOT NULL` (which\n     eliminates null-check branches in execution plans), and interleave the edge\n     table into the source node table (`INTERLEAVE IN PARENT {source_node_table}\n     ON DELETE CASCADE`):\n\n     ```sql\n     CREATE TABLE AccountTransfer (\n       src_id      INT64 NOT NULL,\n       dst_id      INT64 NOT NULL,\n       transfer_id INT64 NOT NULL,\n     ) PRIMARY KEY (src_id, dst_id, transfer_id),\n       INTERLEAVE IN PARENT Account ON DELETE CASCADE;\n     ```\n\n   - Prefer `INT64` keys (bit-reversed sequence or random\/hashed `INT64`) for\n     node and edge keys on traversal-heavy graphs. If you need UUIDs, use the\n     native `UUID` type rather than `STRING(36)`: 36-byte string keys widen\n     secondary indexes and make multi-hop joins slower and more CPU-intensive\n     than 8-byte `INT64` or 16-byte native `UUID` keys.\n2. **Advanced \u2014 Co-Locate Strict 1:N Containment Child Node Tables\n   (`INTERLEAVE IN PARENT`)**:\n   - **Cardinality Guardrail \u2014 Strict `1:N` Containment Only**: Use this\n     advanced technique only when each child node is owned by exactly one\n     parent node and cannot exist without it (strict `1:N` physical\n     containment, such as `IpCard` belonging to one `IpNode`, or `Subnet`\n     belonging to one `Vpc`). If the relationship is many-to-many (`M:N`)\u2014for\n     example, an `IpCard` or `Vrf` that can connect to multiple `IpNode`s\u2014or\n     the child is an independent entity, **never** interleave the child node\n     table under the other node table; keep both as standalone node tables and\n     model the relationship as a dedicated edge table interleaved in the source\n     node table (Step 2.1). Confirm the cardinality with the user before\n     applying this layout.\n   - When strict `1:N` containment applies, prefix the child node's primary key\n     with the parent's primary key and declare `INTERLEAVE IN PARENT\n     {parent_node_table}`. This co-locates parent and child nodes in the same\n     storage split AND lets the child table serve directly as the\n     parent-to-child edge type without a separate edge table:\n\n     ```sql\n     CREATE TABLE IpCard (\n       ip_id   STRING(64) NOT NULL,\n       card_id STRING(64) NOT NULL,\n     ) PRIMARY KEY (ip_id, card_id),\n       INTERLEAVE IN PARENT IpNode ON DELETE CASCADE;\n     -- In CREATE PROPERTY GRAPH:\n     -- NODE TABLES (IpNode KEY (ip_id), IpCard KEY (ip_id, card_id))\n     -- EDGE TABLES (IpCard AS HasCard SOURCE KEY (ip_id) REFERENCES IpNode (ip_id)\n     --   DESTINATION KEY (ip_id, card_id) REFERENCES IpCard (ip_id, card_id))\n     ```\n\n   - **Always Reference the Full Composite Key**: Because interleaving changes\n     the child node's primary key to `({parent_key}, {child_key})`, always\n     declare `KEY ({parent_key}, {child_key})` on the child node table and list\n     every key column in any `SOURCE KEY` or `DESTINATION KEY` referencing it.\n     Referencing only `{child_key}` against a 2-column `KEY` is accepted by\n     Spanner and silently matches every row sharing that partial key.\n3. **Fold `many-to-{0,1}` and `many-to-1` Edges into the Source Node Table**:\n   - When each source node has **at most one** outgoing edge of a given type to\n     a target node (`many-to-{0,1}` or `many-to-1`, such as\n     `(IpNode)-[:ipOnOptical]->(OpticalNode)`), store the target key\n     (`optical_node_id`) as a column directly on the source node table and\n     project that table in both `NODE TABLES` (`IpNode`) and `EDGE TABLES`\n     (`IpNode AS IpOnOpticalEdge`). A `NULL` target key means the node has no\n     such edge (`many-to-0`):\n\n     ```sql\n     CREATE TABLE IpNode (\n       ip_id           STRING(64) NOT NULL,\n       optical_node_id STRING(64),\n       FOREIGN KEY (optical_node_id) REFERENCES OpticalNode (optical_node_id),\n     ) PRIMARY KEY (ip_id);\n     -- In CREATE PROPERTY GRAPH:\n     -- EDGE TABLES (IpNode AS IpOnOpticalEdge\n     --   SOURCE KEY (ip_id) REFERENCES IpNode (ip_id)\n     --   DESTINATION KEY (optical_node_id) REFERENCES OpticalNode (optical_node_id)\n     --   LABEL ipOnOptical)\n     ```\n\n     Folding removes a separate edge table to maintain and write. The query\n     speedup is modest and appears only when a query filters on or returns\n     source-node properties, because the node and its edge come from the same\n     row; key-only traversals perform the same as with an interleaved edge\n     table.\n   - **Enforce the Folded Foreign Key, Never `ON DELETE CASCADE`**: Declare the\n     target-key column as an enforced foreign key to the target node table so it\n     can't point to a missing node. `ON DELETE CASCADE` on this foreign key\n     would delete the source node rows, not just their edges; to delete a\n     target node, first set the referencing target keys to `NULL`. Use\n     `NOT ENFORCED` only for target node tables in datasets with high-degree hub\n     nodes, after confirming the trade-off with the user (see Step 3).\n   - **Cardinality Guardrail \u2014 Do Not Fold `M:N` Edges into Node Tables**: Never\n     fold a many-to-many (`M:N`) edge into a node table by adding `target_id` to\n     the node's primary key, because doing so duplicates the node row for every\n     connected target and corrupts node-level aggregations like\n     `MATCH (n:Node) RETURN COUNT(n)`. Keep `M:N` relationships in a dedicated\n     edge table interleaved in the source node table.\n4. **Consolidate 1:1 Subtype Nodes & Fold 1:1 Intermediate Pass-Through Hops**:\n   - Merge fragmented 1:1 subtype tables (e.g., `RouterNode`, `SwitchNode`,\n     `FirewallNode` sharing the same entity key) into a unified node table (such\n     as `DeviceNode`) with a type discriminator column (such as `device_type`).\n   - If there is no need to model an intermediate pass-through node type in the\n     graph, fold 1:1 pass-through intermediate tables (such as a `CableNode`\n     table where each cable only connects two `Router` endpoints via\n     `Router <-[:terminatedBy]- CableNode -[:terminatedBy]-> Router`) directly\n     into a single edge table so each router-to-router step is 1 hop instead of\n     2. Doing so leaves the intermediate node type (`CableNode`) out of the\n     graph schema: its attributes become edge properties, it can no longer be\n     matched as a node (`MATCH (c:CableNode)`), and it cannot have edges of its\n     own. **Confirm with the user that this is desired before choosing this\n     model** (see Section 5.2 of\n     [Topology & Edge Folding](references\/topology-and-edge-folding.md) for the\n     before-and-after comparison):\n\n     ```sql\n     CREATE TABLE Router (\n       router_id STRING(64) NOT NULL,\n       site_name STRING(128),\n     ) PRIMARY KEY (router_id);\n\n     -- Each cable becomes one edge row between its two routers.\n     CREATE TABLE CableLink (\n       router_id      STRING(64) NOT NULL,\n       peer_router_id STRING(64) NOT NULL,\n       cable_id       STRING(64) NOT NULL,\n       capacity_gbps  INT64,\n       FOREIGN KEY (peer_router_id) REFERENCES Router (router_id),\n     ) PRIMARY KEY (router_id, peer_router_id, cable_id),\n       INTERLEAVE IN PARENT Router ON DELETE CASCADE;\n\n     CREATE OR REPLACE PROPERTY GRAPH CableGraph\n       NODE TABLES (Router)\n       EDGE TABLES (\n         CableLink\n           SOURCE KEY (router_id) REFERENCES Router (router_id)\n           DESTINATION KEY (peer_router_id) REFERENCES Router (router_id)\n           LABEL cableLink PROPERTIES (cable_id, capacity_gbps)\n       );\n     -- One router-to-router hop: MATCH (a:Router)-[:cableLink]->(b:Router)\n     ```\n\n5. **Align Shared Label Properties and Graph-Wide Property Types**:\n   - When multiple node or edge tables share the same `LABEL`, expose the exact\n     same property names and SQL data types across every table declaring that\n     label. Moreover, across the **entire property graph** (even between\n     unrelated labels or between nodes and edges), any property with the same\n     exposed name must have the same SQL data type (`The property declaration of\n     'id' has type conflicts...`). Use column aliases or scalar SQL expressions\n     such as `CAST({col} AS {target_type}) AS {property_name}` in\n     `PROPERTIES (...)` when underlying column types differ.\n\n### Step 3: Optimize Forward & Reverse Edge Traversals\n\nConfigure physical co-location, foreign keys, and covering indexes for all\nremaining edge tables as detailed in\n[Edge Traversal & Indexing](references\/edge-traversal-and-indexing.md):\n\n1. **Forward Traversal (`(src)-[e]->(dst)`)**:\n   - Interleave the edge table into the source node table (`INTERLEAVE IN PARENT\n     {source_node_table} ON DELETE CASCADE`) and add a `FOREIGN KEY\n     ({dst_key_cols}) REFERENCES {dest_node_table} ({dst_key_cols})` on the\n     destination key so the Spanner query optimizer can prune the destination\n     node table scan when queries only need the destination key:\n\n     ```sql\n     CREATE TABLE PersonOwnAccount (\n       person_id   INT64 NOT NULL,\n       account_id  INT64 NOT NULL,\n       create_time TIMESTAMP,\n       FOREIGN KEY (account_id) REFERENCES Account (id),\n     ) PRIMARY KEY (person_id, account_id),\n       INTERLEAVE IN PARENT Person ON DELETE CASCADE;\n     ```\n\n   - For target node tables in datasets with high-degree **hub \/ super nodes**\n     (where individual target nodes receive thousands or millions of concurrent\n     incoming edges), consider a table-level informational foreign key (`NOT\n     ENFORCED`, configured on the table's `FOREIGN KEY` constraint rather than\n     per individual node) to avoid write lock contention on hub rows during\n     concurrent edge inserts while preserving optimizer join elimination.\n     Confirm this trade-off with the user first: informational foreign keys\n     don't prevent dangling edges, and because the optimizer uses them by\n     default, queries can return results that don't match the data if an edge\n     points to a missing node. Keep the foreign key enforced when the user needs\n     strict referential integrity.\n2. **Reverse (`(dst)<-[e]-(src)`) & Any-Direction (`(a)-[e]-(b)`) Traversal**:\n   - Create a **Remote Interleaved Index** keyed by\n     `({dst_key_cols}, {src_key_cols})` with a `STORING ({edge_properties})`\n     clause and `INTERLEAVE IN {dest_node_table}` (without the `PARENT`\n     keyword):\n\n     ```sql\n     CREATE INDEX {edge_table}ByDst\n     ON {edge_table} ({dst_id}, {src_id})\n     STORING ({edge_prop_1}, {edge_prop_2}),\n     INTERLEAVE IN {dest_node_table};\n     ```\n\n   - **Note on `INTERLEAVE IN PARENT` vs. `INTERLEAVE IN`**: While\n     `INTERLEAVE IN PARENT` on a child table requires exact column *name*,\n     type, and order matching, `INTERLEAVE IN {dest_node_table}` on a secondary\n     index (Remote Index) uses *positional type matching*\u2014so `{dst_id}`\n     co-locates in `{dest_node_table}`'s split even when the column name\n     differs from `{dest_node_table}`'s primary key name.\n   - **Store Non-Key Edge Columns by Default**: Including `{src_id}` in the\n     index key and, by default, adding all non-key edge columns to the `STORING`\n     clause (matching the Spanner Graph UI modeler behavior) enables a 100%\n     index-only scan without back-joining to the base edge table. If the edge\n     table has many or wide columns, discuss with the user which frequently\n     accessed edge properties to keep in `STORING`.\n   - **Undirected Queries on Directed Edges (`-[e:Transfers]-{1,4}`)**: Keep\n     plain any-direction traversal backed by the reverse index above. Don't add\n     a second swapped-key reverse edge type in `CREATE PROPERTY GRAPH` for\n     performance: querying it as a label union\n     (`-[:Transfers|ReverseTransfer]->{1,3}`) forces Spanner to evaluate a union\n     across two edge types at every hop, which is slower than\n     `-[:Transfers]-{1,3}`.\n   - **Mutually Symmetric Relationships (`Friend`, `Peer`) Stored as Directed\n     Pairs**: When an application stores each symmetric relationship as two\n     directed rows (`(user_a, user_b)` and `(user_b, user_a)` in one\n     transaction) under `PRIMARY KEY (src_id, dst_id)`, always query with\n     directed `-[:Friend]->` so outgoing traversals seek a single primary-key\n     prefix (especially beneficial on high-degree nodes). Never query a\n     double-stored edge table with undirected `-[:Friend]-`: because both\n     `(A, B)` and `(B, A)` exist in the table, an undirected pattern matches\n     both rows and returns every neighbor twice (and full-scans the table if no\n     reverse index exists).\n\n### Step 4: Add Property-Filtering Indexes & Prevent Dangling Edges\n\nBy default, initial schema creation only requires primary keys and\ntopology\/reverse-traversal indexes (Steps 2\u20133); you do not need to index node or\nedge properties up front. Add the property-filtering indexes in items 1\u20132 below\nonly when the user's queries filter (`WHERE` \/ `FILTER`) or sort (`ORDER BY ...\nLIMIT k`) on specific non-key properties (see Section 3 of\n[Edge Traversal & Indexing](references\/edge-traversal-and-indexing.md)):\n\n1. **Node Property Filtering Indexes**: Create secondary indexes on node\n   columns frequently used in `WHERE` \/ `FILTER` clauses. Use `WHERE {col} IS\n   NOT NULL` (NULL-filtered index) for sparse properties to save storage and\n   write overhead:\n\n   ```sql\n   CREATE INDEX AccountByNickName ON Account (nick_name) STORING (is_blocked);\n   CREATE INDEX AccountByCloseTime ON Account (close_time) WHERE close_time IS NOT NULL;\n   ```\n\n2. **Edge Property Filtering & Per-Node Top-K Indexes**:\n   - For forward or reverse traversal with edge property filters, lead the index\n     with the traversal endpoint key followed by the filtered column, and\n     interleave into the endpoint node table.\n   - For per-node Top-K queries (`ORDER BY e.{ts} DESC LIMIT k` from an anchored\n     node) on high-degree nodes, index `({src_id}, {ts} DESC)` with `STORING` so\n     Spanner pushes `LIMIT k` directly into the index scan and reads only `k`\n     index rows instead of sorting the full adjacency list:\n\n     ```sql\n     -- Forward filter on (src_id, create_time)\n     CREATE INDEX PersonOwnAccountByTime\n       ON PersonOwnAccount (person_id, create_time), INTERLEAVE IN Person;\n     -- Per-node Top-K by create_time DESC\n     CREATE INDEX AccountTransferByTimeDesc\n       ON AccountTransferAccount (src_id, create_time DESC) STORING (amount),\n       INTERLEAVE IN Account;\n     ```\n\n   - Never list the edge table's primary key columns in `STORING`; they are\n     already part of every index and Spanner rejects the DDL.\n3. **Referential Integrity & TTL (`ROW DELETION POLICY`)**:\n   - Prevent dangling edges (edges pointing to deleted nodes) using `INTERLEAVE\n     IN PARENT {source_node_table} ON DELETE CASCADE` and `FOREIGN KEY ... ON\n     DELETE CASCADE` on the destination node.\n   - **Same-Node-Type Edge Exception**: When an edge connects two nodes of the\n     **same** table (e.g., `Account -> Account` in `AccountTransferAccount`),\n     Spanner does not allow combining `INTERLEAVE IN PARENT Account ON DELETE\n     CASCADE` with a second `ON DELETE CASCADE` foreign key to `Account`. If\n     symmetric cascading deletes are required when either endpoint is deleted,\n     make the edge table standalone (not interleaved) with two enforced\n     `FOREIGN KEY ... REFERENCES Account (id) ON DELETE CASCADE` constraints.\n   - When adding a `ROW DELETION POLICY (OLDER_THAN({timestamp_col}, INTERVAL\n     {n} DAY))` to a node table, ensure all attached edge tables either cascade\n     deletes (`ON DELETE CASCADE`) or use informational foreign keys (`NOT\n     ENFORCED`, which leaves dangling edges for the application to clean up),\n     because Spanner rejects node TTL policies if enforced non-cascading child\n     edges block expiration.\n\n### Step 5: Validate Schema DDL & Tear Down Temporary Resources\n\nValidate the generated DDL against the real Spanner engine whenever possible\nbefore presenting it as final:\n\n1. **Preferred \u2014 Validate on a User-Confirmed Spanner Instance**: Ask the user\n   whether they have a Spanner instance (for example, a development or test\n   instance) where you may create a temporary, empty database, and confirm the\n   instance and database name before creating anything (creating a database\n   can incur costs). Apply the complete schema (tables, indexes, and `CREATE\n   PROPERTY GRAPH`) to that empty database:\n   ```bash\n   gcloud spanner databases create {temp_database_id} \\\n     --instance={instance_id} --project={project_id} \\\n     --ddl-file={schema_file}\n   ```\n   Never apply unvalidated DDL to an existing database that contains data.\n2. **Fallback \u2014 Local Spanner Emulator**: If no Spanner instance is available,\n   follow the official\n   [Spanner Emulator guide](https:\/\/docs.cloud.google.com\/spanner\/docs\/emulator.md.txt)\n   to start or connect to the local emulator (if it isn't installed, ask the\n   user before installing it). Create an isolated `gcloud` configuration\n   (`gcloud config configurations create emulator --no-activate`) and pass\n   `--configuration=emulator` on every validation command so DDL never reaches a\n   real instance, then apply the schema with `gcloud spanner databases create\n   {database_id} --instance={instance_id} --ddl-file={schema_file}\n   --configuration=emulator`. Because the emulator doesn't reproduce every\n   engine-specific validation, tell the user that emulator validation is a\n   best-effort check and recommend re-validating on a real instance before\n   production use. If neither `gcloud` nor the emulator is available, verify\n   the DDL statically against the checklist below.\n3. If the compiler reports errors (such as mismatched shared label properties,\n   invalid key arity in `SOURCE KEY` \/ `DESTINATION KEY`, or conflicting\n   `ON DELETE CASCADE` constraints on same-type nodes), fix the DDL and re-run\n   until validation succeeds.\n4. **Clean Up Temporary Validation Resources**: Delete the temporary validation\n   database when finished (`gcloud spanner databases delete {temp_database_id}\n   --instance={instance_id} --quiet`, adding `--configuration=emulator` for the\n   emulator; also delete any temporary emulator instance with `gcloud spanner\n   instances delete {instance_id} --quiet --configuration=emulator`) so the\n   user doesn't incur ongoing storage charges.\n5. Run through the **Schema Verification Checklist** below before returning the\n   final DDL.\n\n## Schema Verification Checklist\n\n- [ ] **No Monotonic Primary Keys & Compact Key Types**: Node and standalone\n      edge primary keys avoid sequential timestamps or auto-incrementing\n      integers as the first key part (prefer random\/bit-reversed `INT64` or\n      native `UUID` over `STRING(36)`).\n- [ ] **Edge Key Prefix & Co-Location**: Dedicated `M:N` edge tables use\n      `PRIMARY KEY ({src_key}, {dst_key}, ...)` and `INTERLEAVE IN PARENT\n      {source_node_table}`.\n- [ ] **Interleaved Child Nodes Are Strict 1:N**: Node tables interleaved in\n      another node table (`INTERLEAVE IN PARENT`) represent strict `1:N`\n      containment; `M:N` relationships between node types use a dedicated edge\n      table instead.\n- [ ] **Folded Pass-Through Node Types Are User-Confirmed**: Any 1:1\n      intermediate node type folded into an edge table (and therefore absent\n      from the graph schema) was explicitly confirmed with the user.\n- [ ] **Cardinality-Safe Edge Folding**: Only `many-to-{0,1}` and `many-to-1`\n      edges are folded into source node tables via `Table AS Edge`; all `M:N`\n      edges remain in separate edge tables so node row counts (`COUNT(n)`) are\n      never inflated, and folded target-key columns use enforced foreign keys\n      without `ON DELETE CASCADE`.\n- [ ] **Reverse Traversal Index Coverage**: Every edge traversed in reverse\n      (`<-[e]-`) or any direction (`-[e]-`) has a secondary index on\n      `({dst_key}, {src_key})` with `STORING (...)` (and `INTERLEAVE IN\n      {dest_node_table}` when key prefixes align).\n- [ ] **Destination Join Elimination**: Edge tables define foreign keys on\n      `DESTINATION KEY` columns (enforced by default; `NOT ENFORCED` only for\n      hub nodes after the user accepts the dangling-edge risk).\n- [ ] **Shared Label Uniformity**: Any `LABEL` shared across multiple tables\n      exposes identical property names and data types (using `CAST` where\n      needed).\n- [ ] **Dangling Edge & TTL Safety**: `ON DELETE CASCADE` and `ROW DELETION\n      POLICY` rules are consistent across parent nodes and attached edges.\n\n## Reference Guides\n\n- [Edge Traversal & Indexing](references\/edge-traversal-and-indexing.md):\n  Complete DDL patterns for forward interleaving, destination foreign keys,\n  reverse covering `STORING` indexes, property-filtering indexes, same-node-type\n  cascades, and TTL policies.\n- [Topology & Edge Folding](references\/topology-and-edge-folding.md): Decision\n  matrix for schematized vs. schemaless graphs, multi-table label alignment, 1:N\n  node hierarchy interleaving, 1:1 subtype consolidation, and cardinality-safe\n  `many-to-{0,1}` \/ `many-to-1` edge folding.\n- [Official Spanner Graph Schema Design Best Practices](https:\/\/docs.cloud.google.com\/spanner\/docs\/graph\/best-practices-designing-schema.md.txt):\n  Google Cloud documentation for Spanner Graph physical schema design.\n\nIf you need product information that's not found in these references, use the\n`search_documents` tool of the Developer Knowledge MCP server.\n","use_cases":["Creating a new Spanner Graph schema with node and edge tables","Optimizing edge traversal performance with covering indexes","Configuring cascading deletes and TTL policies"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/google\/skills\/blob\/c413c1fdc1714f2e4ae44a449b9744348197119c\/skills\/cloud\/spanner-graph-schema-best-practices\/SKILL.md","source_commit":"c413c1fdc1714f2e4ae44a449b9744348197119c","license":null,"version":null,"listing_approved_at":"2026-11-27","created_at":"2026-11-26T11:15:27.000000Z","updated_at":"2026-11-27T07:43:09.000000Z","seo_title":"Design Spanner Graph Schema for Google Cloud","seo_description":"Optimize Spanner Graph schemas with best practices for node tables, edge tables, and indexing. Use for schema design, traversal optimization, and graph topology setup.","seo_keywords":["Spanner Graph schema design","Spanner Graph optimization","Spanner Graph indexing","Spanner Graph topology","Spanner Graph node table","Spanner Graph edge table"]}}