Cypher Query Language Tutorial 🎯

beginner
18 min

Cypher Query Language Tutorial 🎯

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! 📝

What is Cypher Query Language? 💡

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.

Getting Started with Cypher 📝

Basic Syntax

A Cypher query consists of three main parts:

  1. START clause: Specifies the nodes from where the query starts.
  2. MATCH clause: Defines the pattern of nodes and relationships to be matched.
  3. RETURN clause: Specifies what data to return after the match.

Variables and Patterns

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.

Basic Relationship Operations

Cypher allows you to create, delete, and manipulate relationships.

  • Creating a relationship: CREATE (n)-[:RELATIONSHIP_TYPE]->(m)
  • Deleting a relationship: DELETE n-[:RELATIONSHIP_TYPE]->(m)

Navigating Relationships

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

Advanced Cypher 💡

Aggregation Functions

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

Filtering Results

You can filter results using WHERE clause:

START n=node(1) MATCH n-[:FRIENDS_WITH]->m WHERE m.age > 25 RETURN n, m

Ordering Results

Order the results using ORDER BY:

START n=node(1) MATCH n-[:FRIENDS_WITH]->m RETURN m.name ORDER BY m.name ASC

Quiz 💡

Quick Quiz
Question 1 of 1

What does the `START` clause in a Cypher query do?

Keep learning, and happy coding with Cypher! 🎉