Skip to content

MATCH clause: graph queries in SELECT

View as Markdown

CoraDB stores graphs in vertex tables (nodes) and edge tables (relationships), and queries them with a MATCH pattern inside an ordinary SELECT. Because a pattern is just another source in the FROM clause, one statement can traverse the graph and join relational tables, filter with WHERE, aggregate with GROUP BY and sort with ORDER BY. Relational and graph in one query shows how patterns and relational tables are combined.

All examples use the e-commerce sample database: customer, product, category, brand, supplier and city are vertex tables connected by follows, likes, manufactures, part_of, available_at, distributes, resides_in, located_in and located_at edges, while orders, order_items and countries are relational tables.

SELECT <select_expressions>
FROM MATCH [<path_variable> =] [ANY_SHORTEST | ALL_SHORTEST] <graph_pattern> [, <graph_pattern> ...]
[, <table_specification> ...]
[{INNER | LEFT [OUTER] | RIGHT [OUTER]} JOIN MATCH <graph_pattern> [, ...] ON <condition>]
[WHERE <search_condition>]
...
<graph_pattern> ::= <node> [ <edge> <node> ]
<node> ::= ( <alias> : <vertex_table> [WHERE <condition>] )
<edge> ::=
-[ <edge_spec> ]-> -- outgoing (left to right)
| <-[ <edge_spec> ]- -- incoming (right to left)
| -[ <edge_spec> ]- -- either direction
| -> | <- | <-> -- any edge, one hop, without naming it
<edge_spec> ::= [<alias>] : <edge_table> [ | <edge_table> ...] [{<min>,<max>}] [WHERE <condition>]
| {<min>,<max>}
<path_variable> ::= <identifier>
Element Meaning
(cu:customer) A node: the alias cu is bound to rows of the vertex table customer.
-[f:follows]-> An edge of the edge table follows, from the left node to the right node. Its alias (f) gives access to the edge's properties.
-[:follows]-> Same edge without an alias, when its properties are not needed.
<-[...]- / -[...]- Incoming edge / edge in either direction.
->, <-, <-> One edge of any type in that direction.
[:likes|follows] Any of several edge tables.
{min,max} Variable-length path: between min and max hops of that edge type.
(p:product WHERE p.unit_price > 100) Inline filter on a node (or an edge).
pth = ... Path variable, for the graph functions nodes(), relationships(), path_size() …
ANY_SHORTEST / ALL_SHORTEST Return one / all shortest paths between the two end nodes.

Several patterns are separated by commas. Reusing an alias joins the patterns: (cu:customer)-[:follows]->(b:brand), (b:brand)-[:manufactures]->(p:product) describes a two-step path through the same brand b.

Products in the Seafood category:

SELECT p.name
FROM MATCH (p:product)-[:part_of]->(c:category)
WHERE c.name = 'Seafood'
ORDER BY p.name
LIMIT 5;
p.name
Boston Crab Meat
Carnarvon Tigers
Escargots de Bourgogne
Gravad lax
Ikura

A node is counted like a row, so aggregates work as usual. Brands with the most followers:

SELECT b.name, COUNT(cu) AS followers
FROM MATCH (cu:customer)-[:follows]->(b:brand)
GROUP BY b.name
ORDER BY followers DESC, b.name
LIMIT 5;
b.name followers
Nike 209
Adidas 132
Puma 94
Reebok 83
Under Armour 76

Give the edge an alias to read its columns. Every edge in the sample database has a since timestamp; the first customers to follow Nike:

SELECT cu.company_name, f.since
FROM MATCH (cu:customer)-[f:follows]->(b:brand)
WHERE b.name = 'Nike'
ORDER BY f.since
LIMIT 3;
cu.company_name f.since
Robinson PLC 2019-02-28 16:01:36.000
Scott, Mcdaniel and Atkins 2019-03-03 02:13:56.000
Weiss LLC 2019-04-21 08:51:01.000

-> follows an edge from its source to its target, <- the other way round, and - ignores the direction. located_at edges go from a brand to a city, so these two queries return the same row:

SELECT b.name, ci.name FROM MATCH (b:brand)-[:located_at]->(ci:city) WHERE b.name = 'Nike';
SELECT ci.name, b.name FROM MATCH (ci:city)<-[:located_at]-(b:brand) WHERE b.name = 'Nike';
b.name ci.name
Nike Berlin

Writing the arrow the wrong way, (b:brand)<-[:located_at]-(ci:city), matches nothing, because no edge goes from a city to a brand. Use -[:located_at]- when the direction does not matter.

A WHERE inside a node or edge filters while matching. These two queries are equivalent:

SELECT p.name, p.unit_price
FROM MATCH (b:brand WHERE b.name = 'Kari Traa')-[:manufactures]->(p:product WHERE p.unit_price > 100);
SELECT p.name, p.unit_price
FROM MATCH (b:brand)-[:manufactures]->(p:product)
WHERE b.name = 'Kari Traa' AND p.unit_price > 100;
p.name p.unit_price
Côte de Blaye 263.50

List several edge tables with | to match any of them. LABEL() returns the table an edge (or node) belongs to:

SELECT LABEL(r) AS rel, COUNT(*) AS n
FROM MATCH (cu:customer)-[r:likes|follows]->(x:product)
WHERE cu.id = 5
GROUP BY LABEL(r);
rel n
likes 3

Only likes edges are counted: follows edges lead to brands, and the target node here must be a product.

Chain patterns by reusing aliases. Products of the brand Patagonia, with their categories, for customers who follow the brand:

SELECT DISTINCT cu.company_name, p.name AS product, c.name AS category
FROM MATCH (cu:customer)-[:follows]->(b:brand),
(b:brand)-[:manufactures]->(p:product),
(p:product)-[:part_of]->(c:category)
WHERE b.name = 'Patagonia' AND cu.id < 100
ORDER BY 1, 2
LIMIT 5;
cu.company_name product category
Johnson, Lopez and Le Angel Light Running Short Shorts
Johnson, Lopez and Le Ariel Roll Sleeve Sweatshirt Eco Friendly
Johnson, Lopez and Le Ariel Roll Sleeve Sweatshirt Hoodies & Sweatshirts
Johnson, Lopez and Le Breathe-Easy Tank Bras & Tanks
Johnson, Lopez and Le Breathe-Easy Tank Erin Recommends

{min,max} repeats an edge between min and max times. Brands that share at least one follower with Patagonia (customer → brand → customer: exactly two follows hops, in either direction):

SELECT DISTINCT b2.name
FROM MATCH (b1:brand)-[:follows{2,2}]-(b2:brand)
WHERE b1.name = 'Patagonia' AND b1 <> b2
ORDER BY 1
LIMIT 5;
b2.name
ASICS
Adidas
Arc'teryx
Athleta
Birkenstock

How many customers are within 2 to 4 likes hops of customer 5 (they like the same product, or a product liked by such a customer)?

SELECT COUNT(DISTINCT c2.id) AS reachable
FROM MATCH (c1:customer)-[:likes{2,4}]-(c2:customer)
WHERE c1.id = 5 AND c1 <> c2;
reachable
305

ANY_SHORTEST returns one shortest path between each pair of end nodes; ALL_SHORTEST returns every path of that minimal length. Combine them with a path variable to inspect the path.

SELECT c1.company_name AS from_customer, c2.company_name AS to_customer,
path_size(pth) AS hops
FROM MATCH pth = ANY_SHORTEST (c1:customer)-[f:follows{1,6}]-(c2:customer)
WHERE c1.id = 5 AND c2.id = 15;
from_customer to_customer hops
Brown, Roman and Allen Wilson, Frazier and James 6

The two customers are 6 edges apart (customer → brand → customer → brand → customer → brand → customer). There are many equally short routes:

SELECT COUNT(*) AS shortest_paths
FROM MATCH pth = ALL_SHORTEST (c1:customer)-[f:follows{1,6}]-(c2:customer)
WHERE c1.id = 5 AND c2.id = 15;
shortest_paths
148

A path variable holds the whole matched path. Use it with the graph functions: nodes(), relationships(), path_size(), and with list functions such as first(), last(), at() and size().

SELECT path_size(pth) AS path_size,
size(nodes(pth)) AS nodes,
size(relationships(pth)) AS edges
FROM MATCH pth = ANY_SHORTEST (c1:customer)-[f:follows{1,6}]-(c2:customer)
WHERE c1.id = 5 AND c2.id = 15;
path_size nodes edges
6 7 6

Read a property of a node in the path with property_of(node, column, vertex_table). Customers who follow a brand that customer 5 also follows, and the brand that links them:

SELECT property_of(first(nodes(pth)), company_name, customer) AS customer_a,
property_of(at(nodes(pth), 1), name, brand) AS via_brand,
property_of(last(nodes(pth)), company_name, customer) AS customer_b
FROM MATCH pth = (c1:customer)-[f:follows{2,2}]-(c2:customer)
WHERE c1.id = 5 AND c1 <> c2
ORDER BY 2, 3
LIMIT 5;
customer_a via_brand customer_b
Brown, Roman and Allen Skechers Bowen, Burns and Sharp
Brown, Roman and Allen Skechers Howard-Andrade
Brown, Roman and Allen Skechers Johnson Inc
Brown, Roman and Allen Skechers Lang, Hill and Duke
Brown, Roman and Allen Skechers Lowery-Owen

In the WHERE clause, MATCH <pattern> is true when the pattern exists between nodes that are already bound in the FROM clause, and NOT MATCH when it does not. All aliases used in the predicate must be defined in FROM.

Brands whose followers also like one of the brand's products:

SELECT b.name AS brand, COUNT(DISTINCT cu.id) AS fans_who_like_its_products
FROM MATCH (cu:customer)-[:follows]->(b:brand),
(b:brand)-[:manufactures]->(p:product)
WHERE MATCH (cu:customer)-[:likes]->(p:product)
GROUP BY b.name
ORDER BY 2 DESC, 1
LIMIT 5;
brand fans_who_like_its_products
Nike 3
Under Armour 3
Compressport 2
Kappa 2
Tommy Hilfiger 2

The (follower, product) pairs for Nike where the follower does not like the product:

SELECT COUNT(*) AS pairs
FROM MATCH (cu:customer)-[:follows]->(b:brand),
(b:brand)-[:manufactures]->(p:product)
WHERE b.name = 'Nike'
AND NOT MATCH (cu:customer)-[:likes]->(p:product);
pairs
5013

A MATCH can also be used in an EXISTS subquery that refers to an outer alias. Customers in Berlin who follow Adidas:

SELECT cu.company_name
FROM MATCH (cu:customer)-[:resides_in]->(ci:city)
WHERE ci.name = 'Berlin'
AND EXISTS (SELECT 1 FROM MATCH (cu:customer)-[:follows]->(b:brand) WHERE b.name = 'Adidas')
ORDER BY 1
LIMIT 3;
cu.company_name
Bowen, Burns and Sharp
Braun LLC
Gallagher-Cohen

List relational tables next to the patterns and join them in WHERE. In the sample database orders.customer_id and order_items.product_id refer to the customer and product vertices, and city.country_code to the relational countries table.

Cities in Italy, decoding the country code:

SELECT ci.name AS city, co.name AS country
FROM MATCH (ci:city), countries co
WHERE ci.country_code = co.code AND co.name = 'Italy'
ORDER BY 1;
city country
Bergamo Italy
Ravenna Italy
Reggio Emilia Italy
Salerno Italy
Torino Italy

London customers with the most orders:

SELECT cu.company_name, COUNT(o.id) AS orders
FROM MATCH (cu:customer)-[:resides_in]->(ci:city),
orders o
WHERE o.customer_id = cu.id
AND ci.name = 'London'
GROUP BY cu.company_name
ORDER BY orders DESC, cu.company_name
LIMIT 3;
cu.company_name orders
Hicks-Marshall 15
Jordan, Smith and Bartlett 15
Hernandez, Wilson and Johnson 10

MATCH patterns can be used with explicit INNER, LEFT [OUTER] and RIGHT [OUTER] JOIN ... ON, both with other patterns and with tables.

SELECT cu.company_name, b.name AS brand, ci.name AS city
FROM MATCH (cu:customer)-[:follows]->(b:brand)
INNER JOIN MATCH (b2:brand)-[:located_at]->(ci:city) ON b.id = b2.id
WHERE cu.id = 5
ORDER BY 2;
cu.company_name brand city
Brown, Roman and Allen Skechers Madrid

A LEFT JOIN keeps countries that have few or no customers:

SELECT co.name AS country, COUNT(cu.id) AS customers
FROM countries co
LEFT JOIN MATCH (cu:customer)-[:resides_in]->(ci:city) ON ci.country_code = co.code
GROUP BY co.name
ORDER BY customers, co.name
LIMIT 3;
country customers
Ireland 5
Netherlands 5
Poland 5
  • MATCH works only on tables created with CREATE VERTEX TABLE and CREATE EDGE TABLE.
  • Every node needs an alias and a vertex table: (p:product).
  • Aliases bind across all patterns of the same FROM; use different aliases (b, b2) to match two independent nodes of the same table.
  • Comparing two node aliases (c1 <> c2) compares node identity.
  • To keep rows that have no matching graph pattern, use LEFT JOIN MATCH ... ON.