Home / Market / spanner graph query tuning

spanner graph query tuning

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 facto

skill★ 254990 dlgithubApache-2.0Install in CosmosUpstream Source

Documentation & Preview

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

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

  1. 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.

  1. 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}.

  1. Instance Region, Pricing & Teardown: For test instances, default to

regional-us-central1 unless specified otherwise (see Spanner instance configurations, Google Cloud locations, Spanner pricing, and Google Cloud 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):

   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 ..."
  1. Inspect key execution plan metrics (detailed in

references/profile-and-hints-guide.md):

(nested-loop index seeks per input row) or Hash Join (set-based scan + build/probe).

IndexScan, check whether predicates are pushed down into SeekableKeySize: [N] (index key seek) or evaluated after scanning as a Residual Condition.

MATCH hop causes combinatorial path explosion before a downstream filter or GROUP BY.

  1. Apply structural GQL rewrites first (see

Core ISO GQL Query Rewrite Rules and references/gql-rewrite-patterns.md) and validate syntax/compilation quickly with --query-mode=PLAN.

  1. **Apply statement or element hints only if the optimizer chooses a suboptimal

physical plan** (see 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:

  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

comma-separated patterns, which can delay selectivity application:

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

  1. 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.

  1. 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.

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.

FILTER IS_FIRST(@max_edges) OVER (PARTITION BY ...) with SOURCE_NODE_ID(selected_e) inside an edge subquery:

  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

FILTER IS_FIRST(@k) OVER (PARTITION BY a.id) between hops.

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.

LIMIT or index sort order through the LEFT OUTER JOIN (DistributedOuterApply) generated by OPTIONAL MATCH. Bound the optio