Graph query best practices

This document describes best practices for optimizing your BigQuery Graph queries.

Start path traversal from low-cardinality nodes

To keep intermediate result sets small and speed up query execution, write your graph queries so that path traversal starts from lower cardinality nodes, regardless of the direction of path traversal. The following MATCH statements use property filters to reduce the number of possible starting nodes instead of computing all matches and then filtering:

MATCH (p:Person {id: 10})-[own:Owns]->(a:Account)
MATCH (a:Account WHERE balance > 10)<-[own:Owns]-(p:Person)

This is especially important for quantified path queries:

MATCH (p:Person {id: 10})-[own:Owns]->{1,3}(a:Account)

Use ANY or ANY SHORTEST syntax for connectivity checks

Quantified path queries can return duplicate paths between source nodes and destination nodes. If your goal is to check for connectivity and you don't require all possible paths, use ANY or ANY SHORTEST to reduce redundant computations and improve path lookup efficiency. For example, the following MATCH statement uses ANY SHORTEST to keep only one path between each pair of nodes:

MATCH ANY SHORTEST (a1:Account)-[t:Transfers]->{1,3}(a2:Account)

Use directional path traversal

BigQuery Graph schemas are directional, which means that each edge has a source node and a destination node. Although graph query syntax allows path traversal in any direction (for example, -[edge]-), we recommend using directional path traversal (for example, -[edge]-> or <-[edge]-) for better performance. Any direction path traversal might cause performance loss.

The following MATCH statement uses any direction path traversal:

-- Avoid.
MATCH (a1:Account {id: 7})-[t:Transfers]-(a2:Account)

Instead, combine two directional traversals with UNION ALL:

MATCH (