Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install spanner-graph-query-tuning@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin spanner-graph-query-tuning v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install spanner-graph-query-tuning

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/spanner-graph-query-tuning/

Extract the ZIP to .github/skills/ in your repo. The folder name must match spanner-graph-query-tuning for Copilot to auto-discover it.

Skill Files (4)

SKILL.md 22.2 KB
---
name: spanner-graph-query-tuning
metadata:
  version: "1.0.0"
  category: Databases
description: >-
  Tunes and troubleshoots Spanner Graph on Google Cloud ISO GQL queries and
  execution plans. Use when optimizing slow Spanner Graph GQL queries,
  diagnosing distributed cross apply versus hash join execution operators and
  index seek prefixes, eliminating multi-arm star query Cartesian products with
  chained query aggregation, bounding super-node fan-out, decorrelating slow
  subqueries or optional matches, optimizing deep quantified variable-length
  paths, or applying join method, index, and path factorization query hints.
  Don't use for relational-to-property-graph schema mapping over existing
  relational tables (use spanner-relational-to-graph) or physical schema,
  table, and interleaving design (use spanner-graph-schema-best-practices).
---

# Spanner Graph Query Tuning Best Practices

Optimizing ISO GQL queries on Spanner Graph requires aligning pattern matching
and path aggregation with Spanner's distributed query execution engine. Small
syntactic choices in `MATCH` and `NEXT` statements can mean the difference
between a targeted index seek (`SeekableKeySize: [N]`) and a full multi-way
cross apply over millions of intermediate paths.

## 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).

## Prerequisites & Cloud Environment Setup

Before profiling or executing queries against a Spanner instance (see
`spanner-basics` for general Spanner instance provisioning and MCP setup):

1. **Google Cloud SDK (`gcloud`) & Static Analysis Fallback**: Verify whether
   the CLI is installed (do not install `gcloud` without explicit user
   permission; see
   [Install the Google Cloud SDK](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt)).
   If `gcloud` or live Spanner database access is unavailable, do not block on
   executing `gcloud spanner databases ddl describe` or
   `--query-mode=PROFILE`—instead, perform static GQL query analysis and
   rewrites directly using the user-provided query, DDL, or execution plan and
   the bundled `references/` guides.
2. **Project, Billing & API**: Verify an active Google Cloud project with
   billing enabled (required even when provisioning a free trial instance) is
   configured (`gcloud config set project {project_id}`) and, after the user
   confirms, enable the Spanner API
   (`gcloud services enable spanner.googleapis.com`). Ask the user before
   changing the active project, billing, or enabled APIs, because these commands
   change the user's Google Cloud environment and can incur costs.
3. **Authentication & Identity and Access Management (IAM) Roles**: Authenticate
   via `gcloud auth login` or `gcloud auth application-default login` (or
   `GOOGLE_APPLICATION_CREDENTIALS` for service accounts). Inspecting DDL and
   profiling queries requires `roles/spanner.databaseReader` (or
   `roles/spanner.databaseUser`) on `{database_id}`.
4. **Instance Region, Pricing & Teardown**: For test instances, default to
   `regional-us-central1` unless specified otherwise (see
   [Spanner instance configurations](https://docs.cloud.google.com/spanner/docs/instance-configurations.md.txt),
   [Google Cloud locations](https://cloud.google.com/about/locations),
   [Spanner pricing](https://cloud.google.com/spanner/pricing), and
   [Google Cloud pricing](https://cloud.google.com/pricing)). After benchmarking
   on temporary test resources, remind the user to delete temporary test
   databases
   (`gcloud spanner databases delete {database_id} --instance={instance_id}`) or
   test instances (`gcloud spanner instances delete {instance_id}`) so they do
   not incur ongoing Spanner compute and storage charges.

---

## Closed-Loop Query Profiling Workflow

Never apply join or index hints blindly. Always inspect the database DDL,
profile the baseline query, apply structural GQL rewrites first, validate
compilation with `PLAN`, and re-profile to verify latency and scanned rows:

1. **Fetch the schema DDL and profile the baseline query** using
   `gcloud spanner databases ddl describe` and
   `gcloud spanner databases execute-sql` with `--query-mode=PROFILE` (or
   `--query-mode=PLAN` if the baseline times out):

   ```bash
   gcloud spanner databases ddl describe {database_id} --instance={instance_id}

   gcloud spanner databases execute-sql {database_id} \
     --instance={instance_id} \
     --query-mode=PROFILE \
     --sql="GRAPH MyGraph MATCH ... RETURN ..."
   ```

2. **Inspect key execution plan metrics** (detailed in
   [references/profile-and-hints-guide.md](references/profile-and-hints-guide.md)):
   - **Join Type**: Check whether traversal steps use `Distributed Cross Apply`
     (nested-loop index seeks per input row) or `Hash Join` (set-based scan +
     build/probe).
   - **`SeekableKeySize` vs. `Residual Condition`**: In each `TableScan` or
     `IndexScan`, check whether predicates are pushed down into
     `SeekableKeySize: [N]` (index key seek) or evaluated after scanning as a
     `Residual Condition`.
   - **Row Amplification (`Rows Returned` vs. `Storage Read`)**: Identify which
     `MATCH` hop causes combinatorial path explosion before a downstream filter
     or `GROUP BY`.
3. **Apply structural GQL rewrites first** (see
   [Core ISO GQL Query Rewrite Rules](#core-iso-gql-query-rewrite-rules) and
   [references/gql-rewrite-patterns.md](references/gql-rewrite-patterns.md)) and
   validate syntax/compilation quickly with `--query-mode=PLAN`.
4. **Apply statement or element hints only if the optimizer chooses a suboptimal
   physical plan** (see
   [Hint Selection and Guardrails](#hint-selection-and-guardrails)), and re-run
   `--query-mode=PROFILE` to confirm improvement. If a hint degrades latency,
   revert it immediately.

---

## Core ISO GQL Query Rewrite Rules

Before adding optimizer hints, restructure the GQL query so the cardinality
stays small at every step:

### Rule 1: Start Traversals from the Lowest-Cardinality Anchor Node

Order your `MATCH` patterns so the most selective filter (such as
`WHERE n.id = @id` or a selective indexed property) appears **first** in the
pattern chain:

- **Prefer:**

  ```sql
  GRAPH FinGraph
  MATCH (p:Person {id: @person_id})-[o:Owns]->(a:Account)-[t:Transfers]->(b:Account)
  RETURN a.id AS account_id, b.id AS to_account_id, t.amount
  ```

- **Avoid:** Placing unselective patterns first or writing disconnected
  comma-separated patterns, which can delay selectivity application:

  ```sql
  GRAPH FinGraph
  MATCH (a:Account)-[t:Transfers]->(b:Account),
        (p:Person {id: @person_id})-[o:Owns]->(a:Account)
  RETURN a.id AS account_id, b.id AS to_account_id, t.amount
  ```

### Rule 2: Eliminate Multi-Arm Star Query Cartesian Explosions (3 Patterns)

When a query traverses multiple independent 1:N arms from a hub node (for
example, fetching a consumer's emails, phones, addresses, and accounts, or a
router's interfaces and alarms) in a single comma-separated `MATCH`, Spanner
produces an $M \times N \times K$ **Cartesian product** (or sequential
`DistributedOuterApply` joins with `OPTIONAL MATCH`). Choose one of three
remedies based on the required output shape:

1. **Chained `NEXT` + Early Aggregation or Nested `ARRAY { MATCH ... }`
   Subqueries**: Collapse each arm to 1 row per anchor node via `GROUP BY`
   across `NEXT` stages, or collect each 1:N arm into an array column.
   Subqueries cannot redeclare an outer graph variable, so bind a new variable
   and compare it to the outer one
   (`ARRAY { MATCH (n2)-[:HasEmail]->(e:Email) WHERE n2 = n RETURN e.addr }`).
2. **Factorized Execution Hint (`@{factorized_mode=factorize_both}`)**: When
   flat cross-product output rows are genuinely needed, attach
   `@{factorized_mode=factorize_both}` to the conditionally independent arms
   (`MATCH (a)-[e1]->(a1), @{factorized_mode=factorize_both}(a)-[e2]->(a2)`) so
   Spanner evaluates each branch once ($M + N + K$) before forming the final
   result. Return per-arm columns; with `RETURN COUNT(*)` Spanner rejects the
   hint (`A join in the query cannot be executed in factorized execution mode`).
   Because the final output still materializes the cross product, the hint
   usually gains little, while remedy 1 is much faster for aggregated results;
   prefer remedy 1 and keep the hint only if `PROFILE` shows a gain.
3. **Client-Side Parallel Query Decomposition**: When returning wide property
   lists across 4+ independent entity types for a cluster of anchor nodes,
   execute Query 1 to fetch the anchor/cluster node IDs, then issue concurrent
   1-hop queries (`WHERE n.id IN UNNEST(@anchor_ids)`) for each attribute branch
   in parallel.

### Rule 3: Always Specify Node and Edge Labels Across Every `MATCH` and `NEXT` Block

In schemas with multiple node or edge tables (polymorphic labels), omitting a
label (`MATCH (a)-[e]->(b)`) forces Spanner to generate a `Distributed Union`
across **all** node and edge tables in the property graph.

- **Even more critical across `NEXT`**: When passing a node variable `n` into a
  subsequent `NEXT MATCH (n)-[e:EdgeLabel]->(m:TargetLabel)` stage, **re-specify
  the label on the bound node variable**
  (`MATCH (n:SourceLabel)-[e:EdgeLabel]->(m:TargetLabel)`). Omitting
  `:SourceLabel` on `n` in the second `MATCH` can cause Spanner to scan
  unrelated node tables that share the same edge label.

### Rule 4: Avoid Redundant `NEXT` Self-Joins When Edge Endpoints Are Already Available

When a 1:1 or N:1 relationship has been folded into a node table
(`Table AS Edge`), or when you only need the destination key that is already
stored on the source node or edge row, do not chain an extra `NEXT MATCH` hop
that re-scans the same table by primary key just to project a key column or
check existence. Project the property directly in the initial `MATCH` stage.

### Rule 5: Bound Super-Node Fan-Out with `IS_FIRST` or Hub Exclusion, and Avoid Unbounded `OPTIONAL MATCH + LIMIT`

High-degree "super-nodes" (hub nodes with tens of thousands of incident edges)
can dominate query latency when a multi-hop traversal expands every neighbor.

- **Per-hop edge sampling inside quantified paths**: Use
  `FILTER IS_FIRST(@max_edges) OVER (PARTITION BY ...)` with
  `SOURCE_NODE_ID(selected_e)` inside an edge subquery:

  ```sql
  GRAPH FinGraph
  MATCH (a1:Account {is_blocked: true})
    -[e:Transfers WHERE e IN {
        MATCH -[selected_e:Transfers]->
        FILTER IS_FIRST(@max_edges) OVER (
          PARTITION BY SOURCE_NODE_ID(selected_e)
          ORDER BY selected_e.create_time DESC)
        RETURN selected_e
      }]->{1,5}(a2:Account)
  RETURN a1.id AS src_id, a2.id AS dst_id
  ```

- **Single-hop or midpoint sampling**: Use
  `FILTER IS_FIRST(@k) OVER (PARTITION BY a.id)` between hops.
- **Deterministic hub exclusion inside quantified paths**: When hub nodes (such
  as exchanges, payment processors, or shared system accounts) are not
  meaningful intermediaries, precompute a boolean `is_hub` flag on the node
  table and filter the expansion node at each step:
  `MATCH (src:Account {id: @id})((a:Account WHERE a.is_hub = FALSE)-[e:Transfers]->(b:Account)){1,3}(dst:Account)`.
  Both `IS_FIRST` and hub exclusion intentionally change result semantics to
  bound fan-out: `IS_FIRST` caps per-node degree by sampling edges
  (non-deterministic only when `ORDER BY` is omitted or has ties), whereas hub
  exclusion drops paths through hubs while deterministically returning all
  non-hub paths and avoiding hub neighborhood expansion at every hop. Note that
  hub exclusion requires maintaining `is_hub` and adds a node-property lookup
  per hop.
- **`OPTIONAL MATCH` + `ORDER BY` + `LIMIT` Pitfall**: Spanner cannot push
  `LIMIT` or index sort order through the `LEFT OUTER JOIN`
  (`DistributedOuterApply`) generated by `OPTIONAL MATCH`. Bound the optional
  expansion inside an `IS_FIRST` or an
  `ARRAY { MATCH (a2)-[e]->(x) WHERE a2 = a ORDER BY ... LIMIT k RETURN ... }`
  subquery, or use `MATCH` when optionality is not required.

### Rule 6: Seek Prefix Keys Instead of Post-Filtering

Ensure `WHERE` predicates match the leading columns of the node/edge primary key
or secondary index so the execution plan shows `SeekableKeySize: [1]` (or `[N]`)
rather than `SeekableKeySize: [0]` with a `Residual Condition`. Avoid wrapping
key columns in non-sargable functions (such as `CAST(n.id AS STRING) = @id` or
`LOWER(n.code) = @code`) unless backed by a generated column index.

### Rule 7: Optimize Deep Quantified Paths (`{m, n}`) via Lightweight Recursion, Late Materialization, and `factorize_left`

1. **Do not reference intermediate node group variables inside deep quantified
   paths**: Unreferenced intermediate node variables in
   `((v:Node)-[e:Edge]->(t:Node)){1, 10}` are pruned automatically, **but
   referencing `v` or `t`** (even for `ARRAY_TRANSFORM(t, n -> n.id)`, or
   binding `MATCH p = ...` and calling `NODES(p)`) forces `RecursiveScan` to
   scan `Node` at every hop and accumulate full `ARRAY<GRAPH_NODE>` structs
   (with all `Node` columns) in the recursion buffer. Instead, read intermediate
   endpoint keys from the edge group variable
   (`ARRAY_TRANSFORM(e, el -> el.to_id)`).
2. **Defer wide property lookups across multi-stage queries (late
   materialization)**: When grouping, ranking (`ORDER BY ... LIMIT`), or
   filtering reachable nodes across `NEXT` stages on wide node tables, carry
   only lightweight key columns (`dst.id`, satisfied from `e.to_id` via
   foreign-key join elimination without scanning `Node`) through intermediate
   stages, and join `(dst:Node)` in the final `NEXT` stage to fetch wide columns
   only for surviving keys.
3. **Deduplicate converging paths before target node lookup
   (`@{factorized_mode=factorize_left}`)**: When many multi-hop paths converge
   on the same destination nodes, attach `@{factorized_mode=factorize_left}`
   before the destination node
   (`-[e:Transfers]->{1,3}@{factorized_mode=factorize_left}(a2:Account)`) so
   Spanner deduplicates destination keys before probing the `Account` table.
   Return per-path or destination columns: with `RETURN COUNT(*)` Spanner
   rejects the hint
   (`A join in the query cannot be executed in factorized execution mode`). The
   payoff grows with the convergence ratio (at moderate convergence it mainly
   reduces destination lookups and rows scanned, with little change in latency),
   so confirm the gain with `PROFILE`.

### Rule 8: Avoid `ARRAY_AGG` with `IN UNNEST` and Correlated `EXISTS` Subquery Anti-Patterns

1. **Never pass node sets across `NEXT` via `ARRAY_AGG(n.id)` +
   `WHERE n.id IN UNNEST(ids)`**: Aggregating IDs into an array and unnesting
   them in the next stage forces a full table scan with per-row `ArrayUnnest`.
   Pass the bound node variable directly
   (`RETURN DISTINCT n NEXT MATCH (n:Label)...`).
2. **Decorrelate `EXISTS { MATCH ... }` subqueries via `OPTIONAL MATCH`**:
   Correlated `EXISTS` / `NOT EXISTS` subqueries inside `WHERE` (especially
   inside `OR` disjunctions or after `OPTIONAL MATCH`) often execute row-by-row
   via `CrossApply`. Note that a subquery cannot redeclare an outer graph
   variable (`NOT EXISTS { MATCH (a)-[:Transfers]->(b) }` fails with
   `redefining graph element variables in a subquery is not allowed`), and the
   accepted form `NOT EXISTS { MATCH (a2)-[:Transfers]->(b) WHERE a2 = a }` runs
   as an unpushed correlated `Anti-Semi Apply` that re-scans its node table for
   every outer row. Rewrite `NOT EXISTS` directly into
   `OPTIONAL MATCH (a)-[:Transfers]->(b) FILTER b IS NULL` (no `NEXT` needed
   unless following an aggregation like `GROUP BY`), which compiles into a
   set-based hash anti-semi join. For positive `EXISTS`, use `MATCH` and
   deduplicate with `FILTER IS_FIRST(1) OVER (PARTITION BY ...)` or `DISTINCT`
   if multiple edges can match per outer row.

---

## GQL Semantic & Syntax Guardrails

All GQL query rewrites must preserve these syntax and semantic invariants:

- **`WHERE` vs. `FILTER` with `OPTIONAL MATCH`**: Place predicates on optional
  pattern variables inside `OPTIONAL MATCH ... WHERE ...` (evaluated during the
  outer join). Placing them in a trailing `FILTER` clause filters the post-join
  table and silently turns the outer join into an inner join.
- **`ORDER BY` Placement**: In GQL, `ORDER BY` is ignored unless it is the final
  clause of the query (`RETURN ... ORDER BY score DESC LIMIT 10`) or is
  immediately followed by `LIMIT` (`ORDER BY score DESC LIMIT 10 RETURN ...`,
  not `ORDER BY score DESC RETURN ... LIMIT 10`).
- **Returning Graph Elements (Final Top-Level `RETURN` Only)**: Returning raw
  node, edge, or path variables (`RETURN n`) fails with
  `Returning expressions of type GRAPH_ELEMENT is not allowed` **only** when
  `RETURN` is the final statement of the top-level GQL query, because Spanner
  cannot return `GRAPH_ELEMENT` columns directly to the client. Intermediate
  `RETURN n NEXT ...` stages, `WITH n`, and subquery `RETURN`s (such as
  `e IN { MATCH -[selected_e:Transfers]-> ... RETURN selected_e }`) **do** allow
  raw graph elements—pass them directly and do **not** wrap intermediate
  variables in `TO_JSON(n)`. Project explicit properties (`RETURN n.id, n.name`)
  or `TO_JSON(n)` only in the final top-level `RETURN`.
- **Unique Output Column Names (`RETURN` and `WITH`)**: Every column in a
  `RETURN` or `WITH` statement needs a distinct name. `RETURN a.id, b.id` or
  `WITH a.id, b.id` fails with `Ambiguous name: id`; alias duplicates
  (`RETURN a.id AS src_id, b.id AS dst_id`).
- **Reserved Words as Labels**: `Order`, `Group`, and `Contains` (among other
  GQL/SQL keywords) must be escaped in backticks when used as labels or aliases
  (`` (o:`Order`) ``, `` -[:`Contains`]-> ``).
- **Carrying Values Across `NEXT`**: A column produced by a previous statement
  can be referenced only in the outermost `WHERE` of the next `MATCH`: write
  `MATCH (dst:Part) WHERE dst.part_id = target_part_id`, not
  `MATCH (dst:Part {part_id: target_part_id})`.

---

## Hint Selection and Guardrails

Use hints only after verifying with `--query-mode=PROFILE` that the default
optimizer plan is suboptimal. Full syntax and operator diagnostics are in
[references/profile-and-hints-guide.md](references/profile-and-hints-guide.md).

**Hint placement (verified on Spanner)**: element hints go *first* inside the
node or edge pattern (`(@{FORCE_INDEX=Idx} n:Label {...})`,
`-[@{FORCE_INDEX=Idx} e:Label]->`); `JOIN_METHOD` is a traversal hint placed
*between* elements (`-[e:Label]-> @{JOIN_METHOD=HASH_JOIN} (m:Label)`) or at
statement level before `GRAPH`. Writing a hint after the label
(`-[e:Label @{...}]->`) is a syntax error.

| Workload Pattern | Recommended Hint Strategy | Why |
| :--- | :--- | :--- |
| **Selective Anchor Traversal** (1 or a few starting nodes, 1–3 hops) | Default optimizer plan (`Distributed Cross Apply`), or element hint `(@{FORCE_INDEX=IdxName} n:Label ...)` if the wrong index is chosen | `Apply Join` performs targeted B-tree point seeks (`SeekableKeySize >= 1`) proportional only to the anchor fan-out. |
| **Unselective / Bulk Graph Traversal** (scanning a large fraction of nodes/edges across the graph) | Statement hint `@{JOIN_METHOD=HASH_JOIN}` before `GRAPH`, or traversal hint `-[e:Label]-> @{JOIN_METHOD=HASH_JOIN} (m:Label)`, only if `PROFILE` shows a `Distributed Cross Apply` probing millions of rows | Replaces millions of random per-row RPC index probes (`Distributed Cross Apply`) with sequential table/index scans and in-memory hash probes. The optimizer often picks a `Hash Join` for bulk scans automatically (where forcing `APPLY_JOIN` is slower). |
| **Selective Reverse Traversal (`<-[]-`)** | `<-[@{FORCE_INDEX=EdgeReverseIdx} e:EdgeLabel]-` (optionally with traversal hint `@{JOIN_METHOD=APPLY_JOIN}`) | Forces Spanner to seek the reverse secondary index on `(dest_id, src_id)` rather than scanning the forward edge table. |
| **Converging Linear / Quantified Paths** | `-[e:Edge]->{1,3}@{factorized_mode=factorize_left}(dst:Node)` (return per-path or destination columns, not `COUNT(*)`) | Deduplicates converging paths by destination key before looking up `dst` node properties. Pays off only at high convergence ratios; verify with `PROFILE`. |
| **Multi-Arm Star Pattern** (when flat cross-product output is needed) | `MATCH (a)-[e1]->(n1), @{factorized_mode=factorize_both}(a)-[e2]->(n2)` (return per-arm columns, not `COUNT(*)`) | Evaluates conditionally independent arms once ($M + N$) instead of via nested loops ($M \times N$). Prefer Rule 2 remedy 1 unless flat cross-product rows are required and `PROFILE` shows a gain. |

### Critical Hint Guardrails (When NOT to Use Hints)

1. **Do NOT force `@{JOIN_METHOD=HASH_JOIN}` on quantified variable-length path
   patterns (`-[e:Edge]->{1,3}`)** or when foreign-key / schema optimizations
   allow Spanner to eliminate intermediate node table joins. Overriding the join
   method inside quantified paths forces full-table build/probe scans at every
   recursion depth instead of expanding only the active frontier, which is much
   slower on anchored `{1,3}` traversals.
2. **Do NOT force `@{JOIN_METHOD=HASH_JOIN}` on highly selective point lookups**
   without an anchoring filter on the build side; a `Hash Join` without a
   selective build-side filter may scan the entire target table.
3. **Always verify with `PROFILE`**: If a hint increases `Total elapsed time` or
   `Rows scanned`, remove it immediately.

---

## Reference Guides

- **[GQL Rewrite Patterns](references/gql-rewrite-patterns.md)**: Detailed
  before-and-after ISO GQL query transformations for anchor ordering, chained
  `NEXT` early aggregation, label enforcement across `NEXT`, folded-edge
  projection, `IS_FIRST` and hub-exclusion super-node bounding, `OPTIONAL MATCH`
  subquery decorrelation, and quantified-path lightweight recursion and late
  materialization.
- **[PROFILE and Hints Guide](references/profile-and-hints-guide.md)**: How to
  read `gcloud spanner databases execute-sql --query-mode=PROFILE` output
  (`Distributed Cross Apply`, `Hash Join`, `SeekableKeySize`,
  `Residual Condition`) and exact syntax for statement-level, node-level, and
  edge-level hints.
- **Official Spanner Graph Query Tuning Documentation**:
  [Spanner Graph query tuning best practices](https://docs.cloud.google.com/spanner/docs/graph/best-practices-tuning-queries.md.txt)

If you need product information that's not found in these references, use the
`search_documents` tool of the Developer Knowledge MCP server.
references/
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-query-tuning)" \
    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-query-tuning)` 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-query-tuning)
    ```

-   **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.
gql-rewrite-patterns.md 15.3 KB
# ISO GQL Query Rewrite Patterns for Spanner Graph

## Table of Contents

- [1. Anchor-First Pattern Ordering](#1-anchor-first-pattern-ordering): Lines
  22-49
- [2. Chained NEXT with Early Aggregation Instead of Multi-Arm Comma MATCH](#2-chained-next-with-early-aggregation-instead-of-multi-arm-comma-match):
  Lines 53-102
- [3. Explicit Node and Edge Labels Across NEXT Boundaries](#3-explicit-node-and-edge-labels-across-next-boundaries):
  Lines 106-135
- [4. Eliminating Redundant NEXT Self-Joins on Folded Edges](#4-eliminating-redundant-next-self-joins-on-folded-edges):
  Lines 139-163
- [5. Bounding Super-Node Fan-Out with IS_FIRST or Hub Exclusion](#5-bounding-super-node-fan-out-with-is_first-or-hub-exclusion):
  Lines 167-230
- [6. Eliminating `ARRAY_AGG` and `IN UNNEST` Anti-Pattern Across `NEXT`](#6-eliminating-array_agg-and-in-unnest-anti-pattern-across-next):
  Lines 234-267
- [7. Decorrelating `EXISTS` Subqueries via `OPTIONAL MATCH`](#7-decorrelating-exists-subqueries-via-optional-match):
  Lines 271-313
- [8. Deep Quantified Path Optimization: Lightweight Recursion and Late Materialization](#8-deep-quantified-path-optimization-lightweight-recursion-and-late-materialization):
  Lines 317-408

## 1. Anchor-First Pattern Ordering

Always place the node or edge pattern with the highest selectivity (smallest
number of matching rows) at the very beginning of the `MATCH` pattern.

### Anti-Pattern (Unselective Hop First)
```sql
GRAPH FinGraph
MATCH (a:Account)-[t:Transfers]->(b:Account),
      (p:Person {id: @person_id})-[o:Owns]->(a:Account)
WHERE t.amount > 1000
RETURN p.name, a.id AS account_id, b.id AS to_account_id, t.amount
```
Why it is slow: Comma-separated patterns or placing the unselective
`(a)-[t:Transfers]->(b)` hop first can cause the query planner to evaluate or
materialize a broader intermediate set before applying the single-row anchor
`p.id = @person_id`.

### Optimized Pattern (Single Connected Path Starting at Anchor)
```sql
GRAPH FinGraph
MATCH (p:Person {id: @person_id})-[o:Owns]->(a:Account)-[t:Transfers]->(b:Account)
WHERE t.amount > 1000
RETURN p.name, a.id AS account_id, b.id AS to_account_id, t.amount
```
Why it is fast: Spanner seeks `Person(id = @person_id)` directly
(`SeekableKeySize: [1]`), traverses interleaved or indexed `Owns` edges for that
single person, and expands only that person's `Transfers`.

---

## 2. Chained NEXT with Early Aggregation Instead of Multi-Arm Comma MATCH

When a query starts at an anchor node `a` and expands multiple independent 1:N
relationships—such as `(a)-[:HasDevice]->(d:Device)` and
`(a)-[:HasAlert]->(al:Alert)`—putting both arms in a single comma-separated
`MATCH` produces a **Cartesian product** (`|Devices| x |Alerts|`) per anchor
node.

### Anti-Pattern (Multi-Arm Comma MATCH Cartesian Explosion)
```sql
GRAPH NetworkGraph
MATCH (s:Site {region_id: @region_id})-[:HostsRouter]->(r:Router),
      (r)-[:HasInterface]->(i:Interface),
      (r)-[:HasAlarm]->(a:Alarm)
WHERE a.severity = 'CRITICAL'
RETURN r.router_id,
       COUNT(DISTINCT i.interface_id) AS interface_count,
       ARRAY_AGG(DISTINCT a.alarm_id) AS critical_alarms
GROUP BY r.router_id
```
Why it is slow: If a router has 200 interfaces and 50 critical alarms, the
single `MATCH` block generates `200 * 50 = 10,000` intermediate rows per router,
and then burns CPU deduplicating them with `COUNT(DISTINCT ...)` and
`ARRAY_AGG(DISTINCT ...)`.

### Optimized Pattern (Linear Chained NEXT with Per-Stage Aggregation)
```sql
GRAPH NetworkGraph
MATCH (s:Site {region_id: @region_id})-[:HostsRouter]->(r:Router)-[:HasAlarm]->(a:Alarm)
WHERE a.severity = 'CRITICAL'
RETURN r, ARRAY_AGG(a.alarm_id) AS critical_alarms
GROUP BY r

NEXT

MATCH (r:Router)-[:HasInterface]->(i:Interface)
RETURN r.router_id,
       COUNT(i.interface_id) AS interface_count,
       ANY_VALUE(critical_alarms) AS critical_alarms
GROUP BY r.router_id
```
Why it is fast:

1. Stage 1 filters routers down to only those with critical alarms
   (`WHERE a.severity = 'CRITICAL'`) and collapses the cardinality back to **1
   row per `r`** via `GROUP BY r`.
2. Stage 2 expands `:HasInterface` only once per surviving router, avoiding the
   `200 x 50` Cartesian product and eliminating expensive `DISTINCT`
   deduplication. (`critical_alarms` is carried with `ANY_VALUE` because Spanner
   does not allow `GROUP BY` on an `ARRAY` column.)

---

## 3. Explicit Node and Edge Labels Across NEXT Boundaries

When a variable `r` is bound in Stage 1 and passed via
`RETURN r NEXT MATCH (r)...` to Stage 2, always re-specify the node label on `r`
in Stage 2 (`MATCH (r:Router)...`) if the property graph contains multiple node
tables or shared edge labels.

### Anti-Pattern (Unlabeled Bound Node in NEXT Stage)
```sql
GRAPH NetworkGraph
MATCH (s:Site {site_id: @site_id})-[:HostsRouter]->(r:Router)
RETURN r
NEXT
MATCH (r)-[e:LocatedIn]->(z:Zone)
RETURN r.router_id, z.zone_name
```
Why it is slow: If `:LocatedIn` is an edge label shared by multiple source node
tables (`Router`, `Rack`, `Switch`), omitting `:Router` on `(r)` in the second
`MATCH` can cause Spanner to build a polymorphic union scan across all tables
that participate in `:LocatedIn`.

### Optimized Pattern (Explicit Labels in Every MATCH Stage)
```sql
GRAPH NetworkGraph
MATCH (s:Site {site_id: @site_id})-[:HostsRouter]->(r:Router)
RETURN r
NEXT
MATCH (r:Router)-[e:LocatedIn]->(z:Zone)
RETURN r.router_id, z.zone_name
```

---

## 4. Eliminating Redundant NEXT Self-Joins on Folded Edges

When an `N:1` or `1:1` edge is folded directly into a node table
(`Table AS Edge`) via a foreign-key column (for example, `Router.site_id`), and
a query only needs `site_id` (or needs to verify that `site_id IS NOT NULL`), do
not add a `NEXT MATCH` hop that joins back to `Site` unless you actually read
non-key properties from `Site`.

### Anti-Pattern (Unnecessary Extra Hop for Key Column)
```sql
GRAPH NetworkGraph
MATCH (r:Router {status: 'ACTIVE'})
RETURN r
NEXT
MATCH (r:Router)-[:InstalledAtSite]->(s:Site)
RETURN r.router_id, s.site_id
```

### Optimized Pattern (Direct Property Projection on Folded Key)
```sql
GRAPH NetworkGraph
MATCH (r:Router {status: 'ACTIVE'})
WHERE r.site_id IS NOT NULL
RETURN r.router_id, r.site_id
```

---

## 5. Bounding Super-Node Fan-Out with IS_FIRST or Hub Exclusion

In scale-free graphs, a small percentage of hub nodes ("super-nodes") may have
10,000+ incident edges. Expanding all incident edges of a super-node during
multi-hop path exploration can cause latency spikes and out-of-memory errors.

### Anti-Pattern (Unbounded Multi-Hop Expansion Through Hubs)
```sql
GRAPH FinGraph
MATCH (a1:Account {is_blocked: true})-[e:Transfers]->{1, 5}(a2:Account)
RETURN a1.id AS src_id, a2.id AS dst_id
```

### Optimized Pattern A: Per-Hop Edge Sampling Inside Quantified Paths (`FILTER IS_FIRST`)
```sql
GRAPH FinGraph
MATCH (a1:Account {is_blocked: true})
  -[e:Transfers WHERE e IN {
      MATCH -[selected_e:Transfers]->
      FILTER IS_FIRST(@max_edges) OVER (
        PARTITION BY SOURCE_NODE_ID(selected_e)
        ORDER BY selected_e.create_time DESC)
      RETURN selected_e
    }]->{1, 5}(a2:Account)
RETURN a1.id AS src_id, a2.id AS dst_id
```
Why it is fast: At each hop of the `{1, 5}` traversal, the subquery samples at
most `@max_edges` recent outgoing edges per source node
(`PARTITION BY SOURCE_NODE_ID(selected_e)`), preventing exponential fan-out
across high-degree accounts.

### Optimized Pattern B: Midpoint Node Sampling Across `NEXT`
```sql
GRAPH SocialGraph
MATCH (u:User {country: 'FR'})-[:Follows]->(influencer:User)
FILTER IS_FIRST(20) OVER (PARTITION BY u.user_id)
RETURN DISTINCT influencer

NEXT

MATCH (influencer:User)-[:Posted]->(p:Post)
FILTER IS_FIRST(10) OVER (PARTITION BY influencer.user_id ORDER BY p.created_at DESC)
RETURN influencer.user_id, p.post_id
LIMIT 500
```

### Optimized Pattern C: Deterministic Hub Exclusion Inside Quantified Paths
```sql
GRAPH FinGraph
MATCH (src:Account {id: @id})
      ((a:Account WHERE a.is_hub = FALSE)-[e:Transfers]->(b:Account)){1, 3}
      (dst:Account)
RETURN DISTINCT dst.id AS dst_id
```
Why and when to use it: When hub nodes (such as exchanges, clearinghouses, or
payment processors) are not meaningful intermediaries for the business question,
precomputing an `is_hub` boolean column on `Account` and filtering the expansion
node `a` inside the quantified step prevents traversal through hubs. Both
`IS_FIRST` and hub exclusion intentionally change result semantics to bound
fan-out: `IS_FIRST` caps per-node degree by sampling edges (non-deterministic
only when `ORDER BY` is omitted or has ties), whereas hub exclusion drops paths
through hubs while deterministically returning all non-hub paths and avoiding
hub neighborhood expansion at every hop. Caveats: the `is_hub` flag must be
maintained, and filtering `a.is_hub` adds a node lookup per hop.

---

## 6. Eliminating `ARRAY_AGG` and `IN UNNEST` Anti-Pattern Across `NEXT`

When passing matched nodes from one `NEXT` stage to the next, never aggregate
node IDs into an array only to filter by `WHERE n.id IN UNNEST(ids)` in the next
stage.

### Anti-Pattern (`ARRAY_AGG` + `IN UNNEST` Full Table Scan)
```sql
GRAPH SocialGraph
MATCH (p:Person {id: @person_id})-[:Knows]->{1, 2}(f:Person)
RETURN ARRAY_AGG(DISTINCT f.id) AS friend_ids

NEXT

MATCH (f:Person)-[:LocatedIn]->(c:City)
WHERE f.id IN UNNEST(friend_ids)
RETURN f.id, c.name
```
Why it is slow: Aggregating into `ARRAY_AGG` collapses the pipeline into a
single array row, and `WHERE f.id IN UNNEST(friend_ids)` in the next stage can
trigger a full table scan of `Person` with a per-row `ArrayUnnest` check instead
of index seeks.

### Optimized Pattern (Pass Bound Node Variable Directly Across `NEXT`)
```sql
GRAPH SocialGraph
MATCH (p:Person {id: @person_id})-[:Knows]->{1, 2}(f:Person)
RETURN DISTINCT f

NEXT

MATCH (f:Person)-[:LocatedIn]->(c:City)
RETURN f.id, c.name
```

---

## 7. Decorrelating `EXISTS` Subqueries via `OPTIONAL MATCH`

Correlated `EXISTS` or `NOT EXISTS` graph subqueries inside `WHERE` (especially
inside `OR` predicates or after `OPTIONAL MATCH`) often execute row-by-row via
`CrossApply`. Rewriting them with `OPTIONAL MATCH` allows set-based execution
without needing a separate `NEXT` stage.

### Anti-Pattern (Correlated `NOT EXISTS` Subquery in `WHERE`)
```sql
GRAPH FinGraph
MATCH (p:Person {country: 'US'})-[:Owns]->(a:Account)
WHERE NOT EXISTS {
  MATCH (a2:Account)-[:Transfers]->(b:Account {is_blocked: true})
  WHERE a2 = a
}
RETURN p.id AS person_id, a.id AS account_id
```
A subquery cannot redeclare the outer variable `a` (`MATCH (a)-[...]` inside
`EXISTS` is rejected with
`redefining graph element variables in a subquery is not allowed`), so it binds
`a2` and checks `a2 = a`. This form compiles but runs as an `Anti-Semi Apply`
that re-scans the subquery's `Account` table for every outer row: the `a2 = a`
correlation is not pushed into the subquery's node scan, so the query can time
out on large inputs.

### Optimized Pattern (`OPTIONAL MATCH` + `FILTER b IS NULL`)
```sql
GRAPH FinGraph
MATCH (p:Person {country: 'US'})-[:Owns]->(a:Account)
OPTIONAL MATCH (a)-[:Transfers]->(b:Account {is_blocked: true})
FILTER b IS NULL
RETURN p.id AS person_id, a.id AS account_id
```
Why it is fast: `OPTIONAL MATCH` chains directly after `MATCH` in the same
linear query (a preceding `NEXT` is needed only after an aggregation such as
`GROUP BY`), and Spanner decorrelates `OPTIONAL MATCH ... FILTER b IS NULL` into
a set-based **hash anti-semi join**. Here the trailing `FILTER b IS NULL` is the
intended anti-join check, not the `WHERE` vs. `FILTER` mistake (`SKILL.md`
`GQL Semantic & Syntax Guardrails`) where filtering a non-null property of `b`
in `FILTER` turns an outer join into an inner join. For a positive
`EXISTS { MATCH ... }` check, rewrite to `MATCH` and deduplicate with
`FILTER IS_FIRST(1) OVER (PARTITION BY ...)` or `RETURN DISTINCT` if multiple
edges can match per outer row.

---

## 8. Deep Quantified Path Optimization: Lightweight Recursion and Late Materialization

Unreferenced intermediate node variables inside
`((v:Part)-[e:Supplies]->(t:Part)){1, 8}` are pruned automatically by Spanner
Graph. Memory blowups and redundant wide-table scans in deep quantified paths
come from two distinct sources: **referencing** intermediate node group
variables inside recursion, and **carrying wide node properties** through
high-cardinality aggregations or multi-stage `NEXT` pipelines before filtering
or limiting.

### Pattern 8A: Project Hop Keys from Edge Group Variables Instead of Node Group Variables

#### Anti-Pattern (Referencing Intermediate Node Group Variable `t` in Recursion)
```sql
GRAPH SupplyChainGraph
MATCH (src:Part {part_id: @part_id})
      ((v:Part)-[e:Supplies]->(t:Part)){1, 8}
      (dst:Part)
RETURN dst.part_id,
       ARRAY_TRANSFORM(t, n -> n.part_id) AS hop_part_ids
```
Why it is slow: Even though `ARRAY_TRANSFORM` only projects `n.part_id`,
referencing the node group variable `t` (or binding `MATCH p = ...` and calling
`NODES(p)`) forces `RecursiveScan` to scan `Part` at every hop and accumulate
`ARRAY<GRAPH_NODE<Part>>` structs containing all columns of `Part` (including
wide columns such as `manufacturer_details`) in the recursion buffer.

#### Optimized Pattern (Read Hop Keys from Edge Group Variable `e`)
```sql
GRAPH SupplyChainGraph
MATCH (src:Part {part_id: @part_id})
      (()-[e:Supplies]->()){1, 8}
      (dst:Part)
RETURN dst.part_id,
       ARRAY_TRANSFORM(e, el -> el.dst_part_id) AS hop_part_ids
```
Why it is fast: Unreferenced intermediate nodes are pruned from `RecursiveScan`,
foreign-key join elimination satisfies `dst.part_id` directly from
`e.dst_part_id`, and recursion scans only the narrow `Supplies` edge table.

### Pattern 8B: Late Materialization of Wide Columns Across Multi-Stage `NEXT` Queries

#### Anti-Pattern (Carrying Wide Columns Through Aggregation and Ranking)
```sql
GRAPH SupplyChainGraph
MATCH (src:Part {part_id: @part_id})
      (()-[e:Supplies]->()){1, 8}
      (dst:Part)
RETURN dst.part_id,
       dst.part_name,
       dst.manufacturer_details,
       COUNT(1) AS path_count
GROUP BY dst.part_id, dst.part_name, dst.manufacturer_details
ORDER BY path_count DESC, dst.part_id
LIMIT 100
```
Why it is slow: Spanner probes `Part` across all converging paths before
grouping, carries wide columns (`part_name`, `manufacturer_details`) through
`GROUP BY` and `ORDER BY` (which also fails if `manufacturer_details` is a
non-groupable `JSON` or `ARRAY` column), and discards all but the top 100 rows.

#### Optimized Pattern (Aggregate & Limit on Keys First, Fetch Wide Columns in `NEXT`)
```sql
GRAPH SupplyChainGraph
MATCH (src:Part {part_id: @part_id})
      (()-[e:Supplies]->()){1, 8}
      (dst:Part)
RETURN dst.part_id AS target_part_id,
       COUNT(1) AS path_count
GROUP BY target_part_id
ORDER BY path_count DESC, target_part_id
LIMIT 100

NEXT

MATCH (dst:Part)
WHERE dst.part_id = target_part_id
RETURN dst.part_id,
       dst.part_name,
       dst.manufacturer_details,
       path_count
ORDER BY path_count DESC, dst.part_id
```
Note: a column from the previous statement (`target_part_id`) can be referenced
only in the outermost `WHERE` of the next `MATCH`, not inside a property filter
`{part_id: target_part_id}`.

Why it is fast: Both queries return the exact same top-100 rows, but Stage 1
satisfies `dst.part_id` directly from `e.dst_part_id` via foreign-key join
elimination (zero `Part` scans during recursion, grouping, and ranking), and
Stage 2 fetches wide `Part` properties via 100 point seeks only for the final
winners.
profile-and-hints-guide.md 9.0 KB
# Spanner Graph PROFILE Execution Plans and Hints Guide

## Table of Contents

- [1. Running and Reading PROFILE Execution Plans](#1-running-and-reading-profile-execution-plans):
  Lines 14-52
- [2. Diagnosing Join Operators: Apply Join vs. Hash Join](#2-diagnosing-join-operators-apply-join-vs-hash-join):
  Lines 56-87
- [3. Statement-Level, Node-Level, and Edge-Level Hint Syntax](#3-statement-level-node-level-and-edge-level-hint-syntax):
  Lines 91-160
- [4. Quantified Path and Foreign-Key Join Elimination Guardrails](#4-quantified-path-and-foreign-key-join-elimination-guardrails):
  Lines 164-199

## 1. Running and Reading PROFILE Execution Plans

To inspect the physical execution plan and runtime statistics of a Spanner Graph
GQL query, run:

```bash
gcloud spanner databases execute-sql {database_id} \
  --instance={instance_id} \
  --query-mode=PROFILE \
  --sql="GRAPH FinGraph MATCH (p:Person {id: 1})-[o:Owns]->(a:Account) RETURN a.id"
```

If a query is too slow to complete, replace `--query-mode=PROFILE` with
`--query-mode=PLAN` to inspect the estimated execution plan immediately without
executing the query.

### Key Plan Metrics to Inspect

1. **`SeekableKeySize: [N]` on `TableScan` / `IndexScan` (`Storage Read`)**:
   - Indicates how many prefix columns of the primary key or secondary index are
     bound as direct B-tree range seeks.
   - **`SeekableKeySize: [0]`** means Spanner is performing a **full scan** of
     the table or index and evaluating predicates afterward as a
     `Residual Condition`.
   - **`SeekableKeySize: [1]` (or `[2]`, `[3]`)** means Spanner seeks directly
     to the matching key prefix.
2. **`Residual Condition`**:
   - Filter expressions evaluated *after* rows are read from storage.
   - If a high-selectivity filter appears as a `Residual Condition` on a scan
     with `SeekableKeySize: [0]`, either the query is missing a secondary index
     on that property, the filter is on a non-leading key column, or the column
     is wrapped in a non-sargable expression.
3. **`Rows Returned` vs. `Rows Scanned` across Join Boundaries**:
   - Compare the row counts entering and leaving each `Cross Apply` or
     `Hash Join`.
   - If an intermediate join expands 500 anchor rows into 2,000,000 rows before
     a later `FilterScan` or `HashAggregate` collapses them back to 500 rows,
     reorder the `MATCH` pattern or split it with `NEXT` and early `GROUP BY`
     (see [gql-rewrite-patterns.md](gql-rewrite-patterns.md)).

---

## 2. Diagnosing Join Operators: Apply Join vs. Hash Join

Spanner Graph primarily executes pattern traversals using two physical join
families:

### `Local Distributed Cross Apply` / `Distributed Cross Apply` (`apply_join`)

- **How it works**: For each row produced by the left (outer) input, Spanner
  issues an index/table seek into the right (inner) input using the bound
  source/destination key.
- **When it excels**:
  - Selective traversals starting from 1 to a few thousand anchor nodes.
  - Traversals along interleaved child edge tables
    (`Local Distributed Cross Apply`), where parent and child rows reside in the
    same split.
- **Symptom of failure**: When the left input contains tens of thousands or
  millions of rows (for example, an unselective whole-graph scan or a
  high-fan-out multi-hop expansion), `Distributed Cross Apply` issues millions
  of point probes across splits, causing high CPU and network RPC latency.

### `Hash Join` (`hash_join`)

- **How it works**: Spanner scans the build side once, constructs an in-memory
  hash table, and streams the probe side through it.
- **When it excels**:
  - Bulk or unselective graph queries that touch a significant fraction of a
    node or edge table.
  - Multi-hop analytical aggregations across large subgraphs where sequential
    scans are much faster than millions of random B-tree lookups.
- **Symptom of failure**: When used on a highly selective lookup without a
  pushed-down filter on the scanned side, `Hash Join` may scan an entire
  multi-million-row table just to match 5 anchor rows.

---

## 3. Statement-Level, Node-Level, and Edge-Level Hint Syntax

Spanner Graph supports optimizer hints at the **statement/block level** and at
the **individual node or edge pattern level**.

### Statement-Level Join Method Hint

Applies to the whole query when placed before `GRAPH`:

```sql
@{JOIN_METHOD=HASH_JOIN}
GRAPH FinGraph
MATCH (a:Account)-[t:Transfers]->(b:Account)
WHERE a.Status = 'ACTIVE' AND t.amount > 10000
RETURN b.id, COUNT(t) AS high_value_inbound_count
GROUP BY b.id
```

### Element Hints (`@{FORCE_INDEX=...}`) and Traversal Hints (`@{JOIN_METHOD=...}`)

- **Element hints** go *first* inside a node pattern `(@{...} n:Label {...})` or
  edge pattern `-[@{...} e:Label]->`.
- **Traversal hints** (`JOIN_METHOD`) go *between* an edge pattern and the next
  node pattern: `-[e:Label]-> @{JOIN_METHOD=APPLY_JOIN} (m:Label)`.
- Writing a hint after the label (`(n:Label @{...})` or `-[e:Label @{...}]->`)
  is a syntax error (`Expected "]" but got "@"`).

```sql
GRAPH FinGraph
MATCH (@{FORCE_INDEX=PersonsByEmail} p:Person {email: @email})
      -[o:Owns]-> @{JOIN_METHOD=APPLY_JOIN}
      (a:Account)
      <-[@{FORCE_INDEX=AccountTransferAccountByDestSrc} t:Transfers]- @{JOIN_METHOD=APPLY_JOIN}
      (sender:Account)
RETURN sender.id AS sender_id, t.amount
```

### Common Element & Pattern Hints Reference

- `@{FORCE_INDEX=IndexName}` (element hint, first inside the pattern): Forces
  Spanner to scan the backing node or edge table via the specified secondary
  index (for example, a reverse-traversal covering index on
  `(dest_id, src_id)`).
- `@{FORCE_INDEX=_BASE_TABLE}`: Forces Spanner to scan the primary key of the
  base table instead of a secondary index (valid as an element hint or at
  statement level).
- `@{JOIN_METHOD=HASH_JOIN}`: Forces a hash join for the traversal step
  (traversal hint between elements, or statement level).
- `@{JOIN_METHOD=APPLY_JOIN}`: Forces an apply (nested-loop index lookup) join
  for the traversal step.
- `@{JOIN_METHOD=MERGE_JOIN}`: Forces a sort-merge join when both inputs are
  already ordered by the join key.
- `@{factorized_mode=factorize_left}`: Placed before a target node on a linear
  or quantified path
  (`-[e1:Transfers]->{1,3}@{factorized_mode=factorize_left}(a2:Account)`);
  deduplicates converging paths by destination key before probing the target
  node table. Return per-path or destination columns: with `RETURN COUNT(*)`
  Spanner rejects the hint. The gain depends on the convergence ratio (at
  moderate convergence it mainly reduces rows scanned, with little change in
  latency), so verify it with `PROFILE`.
- `@{factorized_mode=factorize_both}`: Placed on conditionally independent arms
  of a star query
  (`MATCH (a)-[e1]->(a1), @{factorized_mode=factorize_both}(a)-[e2]->(a2)`);
  evaluates each arm independently once ($M + N + K$) before forming the final
  output, avoiding nested-loop re-evaluation ($M \times N \times K$). Spanner
  rejects it when the query aggregates the cross product with `RETURN COUNT(*)`
  (`A join in the query cannot be executed in factorized execution mode`).
  Because the final output still materializes the cross product, prefer chained
  `NEXT` aggregation unless flat rows are needed and `PROFILE` shows an
  improvement.

---

## 4. Quantified Path and Foreign-Key Join Elimination Guardrails

### Guardrail 1: Do NOT Force Hints on Quantified Variable-Length Paths (`{m, n}`)

When executing variable-length quantified paths such as:

```sql
GRAPH NetworkGraph
MATCH (start:Device {device_id: @id})-[:ConnectedTo]->{1, 4}(target:Device)
RETURN DISTINCT target.device_id
```

Do **not** add a statement-level `@{JOIN_METHOD=HASH_JOIN}` (or a hash-join
traversal hint on the quantified hop) unless you have verified in `PROFILE` that
the entire table is being scanned at every depth. On anchored variable-length
paths, a forced hash join forces full-table build/probe scans at each recursion
depth instead of expanding only the active frontier via `Apply Join`, which
multiplies both rows scanned and latency.

### Guardrail 2: Preserve Foreign-Key Endpoint Join Elimination

When a query only projects or filters on the **key column** of a target node `b`
(for example, `MATCH (a:Account)-[t:Transfers]->(b:Account)` returning
`a.id AS src_id, b.id AS dst_id`), Spanner's optimizer can **eliminate the join
to the `Account` table for `b`** if the schema defines a `FOREIGN KEY` (enforced
or `NOT ENFORCED`) from `Transfers(dest_id)` to `Account(id)`, reading `b.id`
directly from `Transfers.dest_id`.

- Informational (`NOT ENFORCED`) foreign keys enable this optimization by
  default, but they don't prevent dangling edges: if an edge points to a missing
  node, queries that rely on the eliminated join can return results that don't
  match the data. Prefer enforced foreign keys, and confirm with the user before
  recommending a `NOT ENFORCED` one (see spanner-graph-schema-best-practices).
- Avoid adding element hints on `b` (`(@{...} b:Account)`) or referencing
  non-key properties of `b` when only `b.id` is needed, as they can force the
  optimizer to materialize the otherwise-eliminated `Account` table scan.

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