Skip to content

Neo4j::Cypher Match

Andreas Ronge edited this page Sep 25, 2012 · 16 revisions

Match

Pattern matching is one of the pillars of Cypher. The pattern is used to describe the shape of the data that we are looking for. Cypher will then try to find patterns in the graph — these are called matching sub graphs.

In Neo4j.rb there are several methods to specify a match pattern by using the <, >, >>, <<, <=> and outgoing and incoming methods.

The <, > and - operators is used when you want to specify relationship type(s) between two nodes.

Example: node > ':knows|friend' > other_node

The <<, <=> and outgoing and incoming or used when you don't care what type of relationship the has.

Example: node >> other_node

Related nodes

The method <=> will generate a pattern match without regard to type or direction.

Example:

Neo4j.query{node(3, 4) <=> :x; node(:x)[:desc] =~ /hej/; :x}
# Same as "START n0=node(3,4) MATCH (n0)--(x) WHERE x.desc =~ /hej/ RETURN x"

Outgoing or Incoming of a Type

If you don't want to specify the direction of the relationship but only the type of relationship you can use the - operator:

Neo4j.query{node(3) - ':knows|friends' - :foo; :foo}
# Same as "START n0=node(3) MATCH (n0)-[:knows|friends]-(foo) RETURN foo"

Outgoing/Incoming Relationships

You can specify the direction of relationship to match.

Example: match all outgoing relationship of any type

Neo4j.query{node(3, 4) >> :x;  :x}
# Same as "START n0=node(3,4) MATCH (n0)-->(x) RETURN x"

By using the outgoing and incoming method you can use the declared has_n/has_one relationship types. Example, return friends of friends

Neo4j.query(Person.find(...)){|person| person.outgoing(Person.friends).outgoing(Person.friends)}
# Same as "START n0=node(some_id) MATCH (n0)-[:`knows`]->(v0),(v0)-[:`knows`]->(v1) RETURN v1"

Paths

A path specified with for example << has a number of useful methods. For example, we can return the length of the path like this:

Neo4j.query { p = node(3) >> :b; p.length }

Available methods for paths, see MatchRelRight

Binding Matching Nodes to Variables

It is often useful to assign a variable to a path (as seen above), relationships or nodes. By doing that you can use the variable as a condition in the WHERE clause or in the RETURN clause.

Example: return all outgoing nodes with property name equal 'andreas'

Neo4j.query { node(3) >> (x = node); x[:name] == 'andreas'; x }
Clone this wiki locally