Skip to content

Neo4j::Cypher Where

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

Where

You specify where clauses by using the ==, !=, not < comparable methods (Comparable) on properties (Property) or the is_a?, property?, exist? on node or relationship variables ([Neo4j::Core::Cypher::Variable|http://rdoc.info/github/andreasronge/neo4j-core/Neo4j/Core/Cypher/Variable])

Example:

Neo4j.query {  n=node(3, 4); n[:desc] == "hej"; n }
# same as START n0=node(3,4) WHERE n0.desc = "hej" RETURN n0

Example for optinal properties

Neo4j.query {  n=node(3, 4); n[:desc?] == "hej"; n }
# same as START n0=node(3,4) WHERE n0.desc? = "hej" RETURN n0

Checking if an property exists:

Neo4j.query {  n=node(3, 1); n.property?(:belt); n }
# same as START n0=node(3,1) WHERE has(n0.belt) RETURN n0

Available methods for variables see Property

none? single? any?

The none?, single? any? methods can be found on both path variable or property array.

Example:

Neo4j.query {  p=node(3)>'*1..3'>:b; p.nodes.none? { |x| x[:age] == 25 }}
# same as START n0=node(3) MATCH m2 = (n0)-[*1..3]->(b) WHERE none(x in nodes(m2) WHERE x.age = 25) RETURN m2

Boolean AND, OR operators

The ruby &, | and ! (only for Ruby 1.9) and not can be used to make compound where statements.

Example:

Neo4j.query { n=node(3, 1); where((n[:age] < 30) & ((n[:name] == 'foo') | (n[:size] > n[:age]))); ret n }
# same as START n0=node(3,1) WHERE (n0.age < 30) and ((n0.name = "foo") or (n0.size > n0.age)) RETURN n0

(use where method below because it is easier to read)

Regular Expression

It uses normal Ruby syntax.

Example: node(:x)[:desc] =~ /hej/

Mixing Match and Where

The DSL will take care of what is a match and what is a where clause. That means you can write queries like this:

node(1) > (rel(:knows)[:since] > 1994) > (node(:other)[:name] == 'foo'); :other

Which is same as :

START n0=node(1) MATCH (n0)-[v1:`knows`]->(other) WHERE v1.since > 1994 and other.name = "foo" RETURN other

Match with WHERE and WHERE_NOT

Cypher allows you to have a match in a where clause, example:

START n0=node(1),interest=node(7) MATCH (n0)<--(person) WHERE (person)-->(interest) RETURN person

Use where and where_not on nodes to achieve the same thing, example

node(1) << node(:person).where{|p| p >> node(7).as(:interest)}; :person

Return

The last statement will be used as the cypher return clause.

Example:

Neo4j.query { a=node(3); b = node(2); ret a[:age], b[:age], (a[:age] - b[:age]).abs}
# same as START n0=node(3),n1=node(2) RETURN n0.age,n1.age,abs(n0.age - n1.age)
# instead or ret you can simply return an array
Clone this wiki locally