Cypher
Cypher Query Language
Neo4j's graph query language. Expresses and traverses nodes and relationships intuitively through ASCII-art-style pattern matching.
Cypher Query Language
Neo4j's graph query language. Expresses and traverses nodes and relationships intuitively through ASCII-art-style pattern matching.
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).
"A person node with the User label is connected to a friend node through a FOLLOWS relationship"
(variable:Label {property: value})-[variable:TYPE {property: value}]->--> (directed), -- (undirected)p = (a)-[*1..3]->(b) (path of 1 to 3 hops)MATCH WHERE RETURN CREATE MERGE DELETE SET WITH ORDER BY LIMIT SKIP UNION UNWIND FOREACH OPTIONAL MATCH
// 사용자 노드 생성
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;
// 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;
// 친구의 친구 (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;
// 사용자별 팔로워 수
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;
// 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;
// 친구가 좋아요한 게시물 추천 (내가 아직 안 본 것)
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;
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)
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.
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.
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.