Welcome to our deep dive into the Cypher Query Language! This powerful tool is Neo4j's graph database's query language, designed to handle data that has complex relationships. Let's embark on a journey to understand, explore, and master Cypher together! 📝
Cypher is a declarative graph query language, designed to handle data that is structured as a graph. Unlike traditional SQL, Cypher is designed to work with nodes (entities) and relationships, making it perfect for representing and querying complex relationships between data.
A Cypher query consists of three main parts:
START clause: Specifies the nodes from where the query starts.MATCH clause: Defines the pattern of nodes and relationships to be matched.RETURN clause: Specifies what data to return after the match.In Cypher, variables are defined using the (node_name) syntax. Patterns are represented using nodes and relationships connected by lines.
Here's a simple example:
START n=node(1)
MATCH n-[:KNOWS]->m
RETURN n, m
In this example, we start with a node with the ID 1, and then find all nodes connected to it through a KNOWS relationship.
Cypher allows you to create, delete, and manipulate relationships.
CREATE (n)-[:RELATIONSHIP_TYPE]->(m)DELETE n-[:RELATIONSHIP_TYPE]->(m)You can traverse relationships using the .<relationship_name> syntax. For example, to find friends of friends:
START n=node(1)
MATCH n-[:FRIENDS_WITH]->m-[:FRIENDS_WITH]->f
RETURN n, m, f
Cypher offers aggregation functions like COUNT, SUM, AVG, MIN, and MAX.
START n=node(1)
MATCH n-[:FRIENDS_WITH]->m
RETURN COUNT(m) AS total_friends
You can filter results using WHERE clause:
START n=node(1)
MATCH n-[:FRIENDS_WITH]->m
WHERE m.age > 25
RETURN n, m
Order the results using ORDER BY:
START n=node(1)
MATCH n-[:FRIENDS_WITH]->m
RETURN m.name
ORDER BY m.name ASC
What does the `START` clause in a Cypher query do?
Keep learning, and happy coding with Cypher! 🎉