Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 30 ยท Cypher and Graph Modeling

Cypher: MATCH, CREATE and patterns

Learn Cypher, Neo4j's query language: draw patterns with ASCII art, create nodes and relationships, match them, filter with WHERE and return properties.

SQL asks you to describe tables and how to join them. Cypher, the query language of Neo4j, asks you to draw the shape you are looking for. Round brackets are nodes, square brackets are relationships, and arrows show direction. If you can sketch "a person who works at a company" on a whiteboard, you can already write most of the query.

Neo4j cannot run on this site, so every Cypher block is read-only: it shows real syntax but was not executed here. To let you see what a pattern does, the JavaScript stand-ins build a tiny graph in memory and match patterns against it with a small hand-written matcher. That matcher is a teaching model; the real planner is far more sophisticated. Before this lesson, read Neo4j and the property graph model if nodes, labels and relationship types are new to you.

Patterns: the core idea

TEXT
(p:Person {name: 'Ada'})-[:WORKS_AT]->(c:Company)

Read it left to right:

  • ( ) is a node. p is a variable you can use later; :Person is a label; {name: 'Ada'} is a property filter.
  • -[ ]-> is a relationship. :WORKS_AT is its type; the arrowhead is its direction.
  • Variables are optional: (:Person)-[:WORKS_AT]->(:Company) matches the same shape but gives you nothing to refer to.
flowchart LR
    P["(p:Person<br/>name: Ada)"] -->|"WORKS_AT"| C["(c:Company<br/>name: Acme)"]

The Cypher pattern above, drawn as the graph it describes.

A relationship always has a type and exactly one direction when stored, but you can match it without caring about direction by dropping the arrowhead: (a)-[:KNOWS]-(b).

CREATE

CREATE adds nodes and relationships:

CYPHER
CREATE (ada:Person  {name: 'Ada',  born: 1815})
CREATE (bob:Person  {name: 'Bob',  born: 1971})
CREATE (acme:Company {name: 'Acme'})
CREATE (ada)-[:WORKS_AT {since: 2019}]->(acme)
CREATE (bob)-[:WORKS_AT {since: 2021}]->(acme)
CREATE (ada)-[:KNOWS]->(bob);

Properties live on nodes and relationships. Property values are numbers, strings, booleans, dates and lists of these; a node can have any properties, and nodes with the same label need not have the same ones. Variables like ada exist only within the statement, so one statement can create several things and connect them.

CREATE always creates. Run the statement twice and you get two Adas. Lesson Cypher: MERGE, SET, DELETE and constraints shows the idempotent alternative.

MATCH, WHERE and RETURN

A read query has the shape MATCH pattern WHERE condition RETURN what:

CYPHER
MATCH (p:Person)-[w:WORKS_AT]->(c:Company {name: 'Acme'})
WHERE p.born > 1900 AND w.since >= 2020
RETURN p.name AS person, w.since AS since
ORDER BY since;

MATCH finds every place in the graph where the pattern fits (a match binds each variable to a real node or relationship). WHERE filters those matches, and RETURN picks what to output. Inline properties such as {name: 'Acme'} are shorthand for an equality test in WHERE.

You can chain patterns to walk several steps:

CYPHER
MATCH (a:Person {name: 'Ada'})-[:KNOWS]->(friend)-[:WORKS_AT]->(c:Company)
RETURN friend.name, c.name;

Here the pattern has two hops, and the unlabeled (friend) accepts any node. Compare that with SQL, where the same question needs two joins and an intermediate table; see SQL joins.

Stand-in: a tiny pattern matcher

The program below stores nodes and relationships in arrays and implements matchPath, which finds all chains that follow a list of steps. It is a stand-in for what MATCH does conceptually, not how Neo4j works inside.

JS Matching a pattern over a small graph

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Two people satisfy the first query (Bob and Cy) and the two-hop query finds Ada's friend Bob and his employer. Notice that the matcher produces whole paths, and RETURN merely picks fields from them. That is the mental model: a match is a path of bound variables.

More on RETURN

CYPHER
MATCH (p:Person)
RETURN p.name AS name, p.born AS born
ORDER BY born DESC
LIMIT 2;

MATCH (p:Person)
RETURN DISTINCT p.born > 1980 AS young;

MATCH (p:Person) WHERE p.name STARTS WITH 'A' RETURN p;
  • AS renames a column; ORDER BY sorts; LIMIT and SKIP page the results.
  • DISTINCT removes duplicate rows.
  • Text predicates: STARTS WITH, ENDS WITH, CONTAINS. Lists use IN: WHERE p.name IN ['Ada', 'Bob'].
  • Returning a whole node (RETURN p) gives its labels and all properties. Returning only the properties you need is cheaper.
  • A missing property is null, and comparisons with null are never true; use IS NULL or IS NOT NULL.

Stand-in: filtering with null

JS Missing properties are null

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Dee appears in neither born > 1900 nor born <= 1900, only in IS NULL. A comparison with a missing value is unknown, and WHERE keeps only rows where the condition is true. SQL treats NULL the same way (see SQL NULL values).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In (p:Person {name: 'Ada'}), what is 'p'?

    p is a variable you can use later in WHERE or RETURN. Person is the label and name is a property.
  2. 2. What happens if you run the same CREATE statement twice?

    CREATE always creates. Without a uniqueness constraint nothing stops duplicates; MERGE is the idempotent alternative.
  3. 3. How do you match a KNOWS relationship in either direction?

    Dropping the arrowhead means 'either direction'. Stored relationships still have one direction.
  4. 4. Why does WHERE p.born > 1900 exclude a person with no born property?

    A missing property reads as null. Any comparison with null is unknown, not true, so the row is filtered out.

Summary

  • Cypher describes a shape with ASCII art: (node)-[:TYPE]->(node), with labels, properties and variables.
  • CREATE adds data and is not idempotent; MATCH ... WHERE ... RETURN finds and projects it.
  • Relationships have a type, one stored direction and their own properties; you may match them ignoring direction.
  • Multi-hop questions are just longer patterns, with no explicit joins.
  • Missing properties are null; use IS NULL for them.
  • The stand-in matcher models what a match is (a bound path); the Cypher itself was not run here.

Next: Cypher: MERGE, SET, DELETE and constraints.