-
Notifications
You must be signed in to change notification settings - Fork 276
Neo4j::Cypher 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
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"
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"
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"
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
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 }
WARNING: Much of the information in this wiki is out of date. We are in the process of moving things to readthedocs
- Project Introduction
- Neo4j::ActiveNode
- Neo4j::ActiveRel
- Search and Scope
- Validation, Uniqueness, and Case Sensitivity
- Indexing VS Legacy Indexing
- Optimized Methods
- Inheritance
- Core: Nodes & Rels
- Introduction
- Persistence
- Find : Lucene
- Relationships
- Third Party Gems & extensions
- Scaffolding & Generators
- HA Cluster