Tutorials

The Complete Cypher Cheat Sheet

by
Ivan Despot

Introduction

Cypher is the most widely adopted, fully specified, and open query language for property graph databases. It provides an intuitive and fast way to work with property graphs.

This article contains some of the most useful and common Cypher queries along with their explanations. Whenever you are not sure how to write a Cypher query, you can just take a look at this cheat sheet and try again. If you are new to graph databases and Cypher, you can also use this post to get acquainted with some of the features that Cypher and Memgraph have to offer.

1. Matching

Find nodes with specific properties

MATCH (c:City)
WHERE c.name = "London"
RETURN c.population_size
  • MATCH (c:City): the MATCH clause specifies a node pattern with the label City and assigns the matches to variable c.
  • WHERE c.name = "London": the WHERE clause filters the matched results to those that have a name property with value London.
  • RETURN c.population_size: the RETURN clause is used to request specific results.

This query can be rewritten without a WHERE clause to achieve the same result.

MATCH (c:City {name: "London"})
RETURN c.population_size

Find nodes with specific relationships

MATCH (city:City)-[:IN]-(country:Country)
WHERE city.name = "London"
RETURN country.name
  • MATCH (city:City)-[:IN]-(country:Country): the MATCH clause specifies a node and relationship pattern with two connected nodes, labeled City and Country, connected by a relationship of type IN.

Match labels

MATCH (c:City)
RETURN c

This query can be rewritten using the WHERE clause to achieve the same result.

MATCH (c)
WHERE c:City
RETURN c

Match multiple labels

MATCH (c:City:Country)
RETURN c

This query can be rewritten using the WHERE clause to achieve the same result.

MATCH (c)
WHERE c:City AND c:Country
RETURN c

Matching nodes with properties in a range

MATCH (c:City)
WHERE c.population_size >= 1000000 AND c.population_size <= 2000000
RETURN c

2. Creating

Create a node

CREATE (c:City {name: "Zagreb", population_size: 1000000})
  • c:City: creates a new node with the label City and assigns it to variable c (which can be omitted if it’s not needed).
  • {name: "Zagreb", population_size: 1000000}: the newly created node has two properties, one with a string value and another with an integer value.

Create nodes with relationships

CREATE (c1:City {name: "UK"}),
       (c2:City {name: "London", population_size: 9000000})
       (c1)<-[r:IN]-(c2)
RETURN c1, c2, r

The CREATE clause is used to create two new nodes and a directed relationship between them.

Create a relationship between existing nodes

MATCH (c1), (c2)
WHERE c1.name = "UK" AND c2.name = "London"
CREATE (c2)-[:IN]->(c1)

This will create a directed relationship of type IN between two existing nodes. If such a relationship already exists, this query will result in a duplicate. To avoid this, you can use the MERGE clause:

MATCH (c1), (c2)
WHERE c1.name = "UK" AND c2.name = "London"
MERGE (c2)-[:IN]->(c1)

3. Updating

Add or update node properties

MATCH (c:Country {name: "UK"})
SET c.name = "United Kingdom"

If you use the SET clause on a property that doesn’t exist it will be created.

Replace all node properties

MATCH (c:Country)
WHERE c.name = "United Kingdom"
SET c = {name: "UK", population_size: "66650000"}
  • SET c = {name: "UK" ...}: this SET clause will delete all existing properties and create the newly specified ones.

Update multiple node properties

MATCH (c:Country)
WHERE c.name = "United Kingdom"
SET c += {name: "UK", population_size: "66650000"}
  • SET c += {name: "UK" ...}: this SET clause will add new properties and update existing ones if they are already set.

Check if a property exists and update it

MATCH (c:Country)
WHERE c.name = "Germany" AND c.language IS NULL
SET c.language = "German"

Because the WHERE clause contains the statement c.language IS NULL, the node will only be matched if it doesn’t have a language property.

Rename a property

MATCH (c:Country)
WHERE c.official_language IS null
SET c.official_language = c.language
REMOVE c.language
  • WHERE c.official_language IS null: the WHERE clause makes sure that you only create the new property in nodes that don’t have a property with the same name.
  • SET n.official_language = n.language: you are technically not renaming a property but rather creating a new one with a different name and the same value.
  • REMOVE n.language: the REMOVE clause is used to delete the old property.

4. Deleting

Delete a node

MATCH (c)-[r]-()
WHERE c.name = "US"
DELETE r, c
  • DELETE r, c: before you can delete a node, all of its relationships need to be deleted first.

This query can be rewritten with the DETACH clause to achieve the same result.

MATCH (c)
WHERE c.name = "US"
DETACH DELETE c

Delete a property

MATCH (c:Country)
WHERE c.name = "US" AND c.language IS NOT null
DELETE c.language

This query will delete the property language from a specific node.

Delete label in every node

MATCH (c)
DELETE c:Country

This query will delete the label Country from every node.

Delete one of multiple labels

MATCH (c)
WHERE c:Country:City
REMOVE c:City

This will delete the label City from every node that has the labels Country and City.

Delete all nodes and relationships

MATCH (n)
DETACH DELETE n

This query will delete the whole database.

5. Constraints

Create a uniqueness constraint

CREATE CONSTRAINT ON (c:City) 
ASSERT c.location IS UNIQUE

This query will make sure that every node with the label City has a unique value for the location property.

Create an existence constraint

CREATE CONSTRAINT ON (c:City) 
ASSERT exists (c.name)

This query will make sure that every node with the label City has the property name.

Check constraints

SHOW CONSTRAINT INFO

This query will list all active constraints in the database.

Drop a uniqueness constraint

DROP CONSTRAINT ON (c:City) 
ASSERT c.location IS UNIQUE

This query will remove the specified uniqueness constraint.

Drop an existence constraint

DROP CONSTRAINT ON (c:City) 
ASSERT exists (c.name)

This query will remove the specified existence constraint.

6. Graph Algorithms

To find out more about the built-in algorithms in Memgraph, take a look at the reference guide.

Breadth First Search

MATCH (c1:City {name: "London"})-[
        edge_list:ROAD_TO *bfs..10
    ]-(c2:City {name: "Paris"}) 
RETURN *

This query will find all paths of length up to 10 between nodes c1 and c2.

Weighted Shortest Path

MATCH (c1:City {name: "London"})-[
        edge_list:ROAD_TO *wShortest 10 (e, n | e.weight) total_weight
    ]-(c2:City {name: "Paris"})
RETURN *

The above query will find the shortest path of length up to 10 nodes between nodes c1 and c2. The length restriction parameter is optional.

7. NetworkX

If you want to know which NetworkX algorithms are available in Memgraph, take a look at the reference guide.

Analyze the whole graph

CALL graph_analyzer.analyze() WITH YIELD *

This query will return various information like the number of nodes, number of edges, average degree, etc.

Find weakly connected components (Union Find)

MATCH (n)-[e]->()
WITH collect(n) AS nodes, collect(e) AS edges
CALL wcc.get_components(nodes, edges) YIELD *
RETURN n_components, components

This query will search the whole graph for weakly connected components.

Calculate PageRank for all nodes

CALL nxalg.pagerank() YIELD *
RETURN node.name AS name, rank 
ORDER BY rank DESC
LIMIT 10

This query will calculate the rank of every node, order them from highest to lowest and return the first 10 results.

8. Other Useful Cypher Queries

Count all nodes

MATCH (n)
RETURN count(n)

This query will return the number of nodes in the database.

Count all relationships

MATCH ()-->()
RETURN count(*)

This query will return the number of relationships in the database.

Limit the number of returned results

MATCH (c:City)
RETURN c
LIMIT 5
  • LIMIT 5: this will limit the number of returned nodes to 5.

Specify an alias for results

MATCH (c:Country)
WHERE c.name = "US"
RETURN c.population_size AS population 

By using AS with the RETURN clause, the property population_size will be returned with an alias.

Conclusion

Cypher is an extensive query language with lots of features, and this cheat sheet is a great starting point for mastering them. You can also go through our Cypher lessons on Memgraph Playground, an online platform for running Cypher queries on live data.

If you have any questions about Cypher that aren’t covered in this article, please take a look at our Cypher manual. Feel free to also share your questions on StackOverflow with the tag memgraphdb or on our community forum.

Table of Contents
Sign up for our Newsletter

Continue Reading