MATCH-nodes in Neo4j

  • Read
  • Discuss

The MATCH clause in neo4j is mostly used for searching. The MATCH clause allows you to specify the patterns of nodes or relationships Neo4j will search for in the database. 

MATCH is frequently combined with a WHERE clause, which gives the MATCH patterns additional constraints or predicates and increases their specificity. 

Predicates should not be viewed as a filter that is applied only after matching because they are a component of the pattern description. This means that WHERE and the MATCH clause to which it belongs should always be combined.

Example graph

The following graph is used for the examples below:

To recreate the graph, run the following cypher query in an empty Neo4j database:

CREATE
  (charlie:Person {name: 'Charlie Sheen'}),
  (martin:Person {name: 'Martin Sheen'}),
  (michael:Person {name: 'Michael Douglas'}),
  (oliver:Person {name: 'Oliver Stone'}),
  (rob:Person {name: 'Rob Reiner'}),
  (wallStreet:Movie {title: 'Wall Street'}),
  (charlie)-[:ACTED_IN {role: 'Bud Fox'}]->(wallStreet),
  (martin)-[:ACTED_IN {role: 'Carl Fox'}]->(wallStreet),
  (michael)-[:ACTED_IN {role: 'Gordon Gekko'}]->(wallStreet),
  (oliver)-[:DIRECTED]->(wallStreet),
  (thePresident:Movie {title: 'The American President'}),
  (martin)-[:ACTED_IN {role: 'A.J. MacInerney'}]->(thePresident),
  (michael)-[:ACTED_IN {role: 'President Andrew Shepherd'}]->(thePresident),
  (rob)-[:DIRECTED]->(thePresident),
  (martin)-[:FATHER_OF]->(charlie)

Get all nodes

By specifying a pattern with a single node and no labels, all nodes in the graph will be returned.

Query

MATCH (n)
RETURN n

Returns all the nodes in the database.

Get all nodes with a label

Find all nodes with a specific label:

Query

MATCH (movie:Movie)
RETURN movie.title

Returns all the nodes with the Movie label in the database.

Related nodes

The symbol — means related to, without regard to type or direction of the relationship. All nodes having some relationship with the original node are returned.

Query

MATCH (director {name: 'Oliver Stone'})--(movie)
RETURN movie.title

Returns all the movies directed by Oliver Stone.

Match with labels

In order to find the nodes by limiting a pattern with labels on nodes, add the labels to the nodes (to be searched) in the pattern.

Query

MATCH (:Person {name: 'Oliver Stone'})--(movie:Movie)
RETURN movie.title

Returns any nodes with the Movie label connected to Oliver Stone.

Leave a Reply

Leave a Reply

Scroll to Top