🗄️ Databases

Cypher

Cypher Query Language

Neo4j's graph query language. Expresses and traverses nodes and relationships intuitively through ASCII-art-style pattern matching.

📖 Detailed Explanation

Cypher is a declarative graph query language developed by Neo4j that retrieves and manipulates graph data through pattern matching. Just as SQL handles table-based data, Cypher handles graph data composed of nodes (Node) and relationships (Relationship).

(person:User)-[:FOLLOWS]->(friend:User)

"A person node with the User label is connected to a friend node through a FOLLOWS relationship"

Core Pattern Syntax

  • Node: (variable:Label {property: value})
  • Relationship: -[variable:TYPE {property: value}]->
  • Direction: --> (directed), -- (undirected)
  • Path: p = (a)-[*1..3]->(b) (path of 1 to 3 hops)

Key Keywords

MATCH WHERE RETURN CREATE MERGE DELETE SET WITH ORDER BY LIMIT SKIP UNION UNWIND FOREACH OPTIONAL MATCH

💻 Code Example

Creating Nodes and Relationships (CREATE)
// 사용자 노드 생성 CREATE (u:User { id: 'user-001', name: '김철수', email: 'chulsoo@example.com', created_at: datetime() }) RETURN u; // 여러 노드와 관계 한 번에 생성 CREATE (alice:User {name: 'Alice'}) CREATE (bob:User {name: 'Bob'}) CREATE (post:Post {title: 'Hello Graph!', content: '...'}) CREATE (alice)-[:FOLLOWS]->(bob) CREATE (alice)-[:WROTE {at: datetime()}]->(post) CREATE (bob)-[:LIKED]->(post) RETURN alice, bob, post;
Basic Query (MATCH + WHERE + RETURN)
// Look up the followers of a specific user MATCH (u:User {name: 'Alice'})<-[:FOLLOWS]-(follower:User) RETURN follower.name, follower.email; // Separate the conditions into a WHERE clause MATCH (u:User)-[:WROTE]->(p:Post) WHERE u.created_at > datetime('2024-01-01') AND p.likes > 10 RETURN u.name, p.title, p.likes ORDER BY p.likes DESC LIMIT 10;
Variable-Length Path Traversal
// 친구의 친구 (2홉 관계) MATCH (me:User {name: 'Alice'})-[:FOLLOWS*2]->(fof:User) WHERE me <> fof // 자기 자신 제외 RETURN DISTINCT fof.name; // 1~3 홉 사이의 연결된 사용자 MATCH path = (a:User {name: 'Alice'})-[:FOLLOWS*1..3]->(b:User) RETURN b.name, length(path) AS distance ORDER BY distance; // 최단 경로 찾기 MATCH (start:User {name: 'Alice'}), (end:User {name: 'Charlie'}) MATCH path = shortestPath((start)-[:FOLLOWS*..10]->(end)) RETURN path, length(path) AS hops;
Aggregation and Grouping
// 사용자별 팔로워 수 MATCH (u:User)<-[:FOLLOWS]-(follower) RETURN u.name, count(follower) AS follower_count ORDER BY follower_count DESC; // 인기 게시물과 작성자 MATCH (u:User)-[:WROTE]->(p:Post)<-[:LIKED]-(liker) WITH u, p, count(liker) AS like_count WHERE like_count >= 5 RETURN u.name AS author, p.title, like_count ORDER BY like_count DESC; // COLLECT로 리스트 생성 MATCH (u:User)-[:FOLLOWS]->(friend:User) RETURN u.name, collect(friend.name) AS friends;
MERGE - Match if It Exists, Create if Not
// Create the user if it does not exist, otherwise use the existing node MERGE (u:User {email: 'new@example.com'}) ON CREATE SET u.name = 'New User', u.created_at = datetime() ON MATCH SET u.last_login = datetime() RETURN u; // Relationship MERGE MATCH (a:User {name: 'Alice'}), (b:User {name: 'Bob'}) MERGE (a)-[r:FOLLOWS]->(b) ON CREATE SET r.since = date() RETURN r;
Recommendation System Query
// 친구가 좋아요한 게시물 추천 (내가 아직 안 본 것) MATCH (me:User {name: 'Alice'})-[:FOLLOWS]->(friend:User) MATCH (friend)-[:LIKED]->(post:Post) WHERE NOT (me)-[:LIKED]->(post) AND NOT (me)-[:WROTE]->(post) WITH post, count(friend) AS friend_likes ORDER BY friend_likes DESC LIMIT 10 RETURN post.title, friend_likes; // 공통 관심사 기반 사용자 추천 MATCH (me:User {name: 'Alice'})-[:INTERESTED_IN]->(topic:Topic) MATCH (other:User)-[:INTERESTED_IN]->(topic) WHERE me <> other AND NOT (me)-[:FOLLOWS]->(other) WITH other, count(topic) AS common_interests WHERE common_interests >= 3 RETURN other.name, common_interests ORDER BY common_interests DESC;
Using Cypher in Python (neo4j driver)
from neo4j import GraphDatabase class Neo4jService: def __init__(self, uri, user, password): self.driver = GraphDatabase.driver(uri, auth=(user, password)) def close(self): self.driver.close() def get_followers(self, username: str) -> list: with self.driver.session() as session: result = session.run(""" MATCH (u:User {name: $name})<-[:FOLLOWS]-(follower:User) RETURN follower.name AS name, follower.email AS email """, name=username) return [dict(record) for record in result] def create_follow_relationship(self, from_user: str, to_user: str): with self.driver.session() as session: session.run(""" MATCH (a:User {name: $from_user}) MATCH (b:User {name: $to_user}) MERGE (a)-[r:FOLLOWS]->(b) ON CREATE SET r.since = date() """, from_user=from_user, to_user=to_user) def recommend_users(self, username: str, limit: int = 10): with self.driver.session() as session: result = session.run(""" MATCH (me:User {name: $name})-[:FOLLOWS]->(friend)-[:FOLLOWS]->(fof) WHERE me <> fof AND NOT (me)-[:FOLLOWS]->(fof) WITH fof, count(friend) AS mutual_friends RETURN fof.name AS name, mutual_friends ORDER BY mutual_friends DESC LIMIT $limit """, name=username, limit=limit) return [dict(record) for record in result] # 사용 service = Neo4jService("neo4j://localhost:7687", "neo4j", "password") followers = service.get_followers("Alice") recommendations = service.recommend_users("Alice", 5)

💬 Real-world conversation examples

Backend developer
"I need to implement a friend-of-a-friend recommendation feature, but the JOINs in SQL are getting too complicated."
Senior developer
"Neo4j is perfect for that kind of relationship traversal. With Cypher, you can express a 2-hop relationship in a single line like MATCH (me)-[:FOLLOWS*2]->(fof). Performance is in the millisecond range even with millions of nodes."
Data Analyst
"To detect fraud, I need to trace the flow of funds between accounts. I want to find accounts connected up to 5 steps away."
DBA
"Cypher's variable-length path traversal is the key. You find paths with (a)-[:TRANSFER*1..5]->(b), and shortestPath() gives you the shortest path right away. That's why the financial sector uses graph DBs a lot."
Junior Developer
"What's the difference between MERGE and CREATE? Don't both of them create data?"
Senior developer
"CREATE always creates something new. Duplicates are possible. MERGE means 'get it if it exists, create it if it doesn't.' You can also handle each case with ON CREATE and ON MATCH. Most of the time, MERGE is used more."

⚠️ Cautions

⚠️ Variable-Length Path Performance

A variable-length path with no upper bound, such as -[:REL*]->, is fatal to performance. Always limit the maximum number of hops, as in -[:REL*1..5]->. If the graph is large, the amount of traversal grows exponentially.

⚠️ Beware of Cartesian Products

Using multiple MATCH clauses with no relationship between them produces a Cartesian product. MATCH (a:User), (b:Post) generates every combination of all Users × all Posts, causing performance to plummet.

⚠️ Indexes Are Essential

Always create an index on the node properties that serve as the starting point of a MATCH. CREATE INDEX FOR (u:User) ON (u.email). Scanning all nodes without an index makes query speed drop sharply.

🔗 Related Terms

📚 Learn More