Neo4j Cypher Queries

Cypher keywords

Like most programming languages, Cypher reserves several words for specific operations within a query. You need to create, read, update, and delete data in Neo4j, and these keywords help perform those operations. This section examines two common keywords in detail; later guides cover more.

MATCH

Cypher’s MATCH keyword searches the database for existing nodes, relationships, labels, properties, or patterns. If you are familiar with SQL, MATCH behaves much like SQL’s SELECT.

You can use MATCH to find all node labels, retrieve a particular node, find every node with a specific relationship, or locate patterns of nodes and relationships.

RETURN

Cypher’s RETURN keyword specifies the values or results returned by a query. It can return nodes, relationships, their properties, or patterns. It is unnecessary for write-only operations but required when reading data.

RETURN becomes important when using node and relationship variables. To retrieve a node, relationship, property, or pattern, assign a variable to the desired data in the MATCH clause.

Cypher examples

The following examples use MATCH and RETURN. Each starts with the intended result and shows a query that can be run in Neo4j Browser.

  • Example 1: Find a labeled node in the Person graph. To return a Person node, assign it a variable such as p.

    MATCH (p:Person)
    RETURN p
    LIMIT 1
    
  • Example 2: Find the node named Tom Hanks in the Person graph. You may choose any variable name as long as later references use the same name.

    MATCH (tom:Person {name: 'Tom Hanks'})
    RETURN tom
    
  • Example 3: Find a Movie directed by Tom Hanks.

    MATCH (:Person {name: 'Tom Hanks'})-[:DIRECTED]->(movie:Movie)
    RETURN movie
    
  • Example 4: Find a movie directed by Tom Hanks, but return only its title.

    MATCH (:Person {name: 'Tom Hanks'})-[:DIRECTED]->(movie:Movie)
    RETURN movie.title
    

Aliasing returned values

Not every property name is as simple as movie.title. Some are difficult to read because they are long, contain several words, use developer terminology, or rely on abbreviations. Such names become especially awkward in reports and other user-facing interfaces.

// Poorly named properties
MATCH (tom:Person {name:'Tom Hanks'})-[rel:DIRECTED]-(movie:Movie)
RETURN tom.name, tom.born, movie.title, movie.released

As in SQL, use the AS keyword to assign simpler aliases and rename fields in the returned results. The following mock example lists a person’s movies with clearer result names.

// Cleaner printed results with aliasing
MATCH (tom:Person {name:'Tom Hanks'})-[rel:DIRECTED]-(movie:Movie)
RETURN tom.name AS name, tom.born AS `Year Born`, movie.title AS title, movie.released AS `Year Released`

Enclose a return alias in backticks when it contains spaces, as in movie.released AS `Year Released` . Backticks are unnecessary for aliases without spaces.

Reference