MATCH¶
The MATCH clause is used to search for patterns in the graph.
Basic Node Match¶
Match all nodes with a label:
Match nodes with specific properties:
Multiple Labels¶
Match nodes with multiple labels:
Relationship Patterns¶
Outgoing Relationships¶
Incoming Relationships¶
Undirected Relationships¶
Any Relationship Type¶
Variable-Length Paths¶
Match paths of variable length:
-- Friends up to 3 hops away
MATCH (u:User {name: 'Alice'})-[:KNOWS*1..3]->(friend)
RETURN DISTINCT friend.name
Shortest path:
Multiple Patterns¶
Match multiple patterns:
MATCH (a:User)-[:KNOWS]->(b:User),
(b)-[:WORKS_AT]->(c:Company)
WHERE a.name = 'Alice'
RETURN a, b, c
Optional Matching¶
Match patterns that may not exist:
Pattern Comprehension¶
Common Patterns¶
Triangle Pattern¶
-- Find triangles (mutual connections)
MATCH (a:User)-[:KNOWS]->(b:User)-[:KNOWS]->(c:User)-[:KNOWS]->(a)
WHERE a.id < b.id AND b.id < c.id
RETURN a, b, c
Star Pattern¶
-- Find users with many connections
MATCH (center:User)-[:KNOWS]->(other:User)
WITH center, count(other) as connections
WHERE connections > 10
RETURN center, connections
ORDER BY connections DESC
Chain Pattern¶
-- Find recommendation chain
MATCH (u:User {name: 'Alice'})-[:KNOWS]->(f)-[:KNOWS]->(fof)
WHERE NOT (u)-[:KNOWS]->(fof)
RETURN DISTINCT fof.name
Performance Tips¶
-
Start with Most Selective Pattern
-
Use Labels
-
Limit Variable-Length Paths
Next Steps¶
- Add filters with WHERE
- Select output with RETURN
- Create data with CREATE
- Read Cypher Introduction