Skip to content

Neo4j::Cypher Where

andreasronge edited this page Oct 1, 2012 · 11 revisions

Filtering of a match is done by using the ==, !=, not < operators on nodes and relationship.

Example: to find my friends who are older then 30 years old

node(42).as(:me) > :friends > (node[:age] > 32)

Which generates START me=node(42) MATCH v2 = (me)-[:`friends`]->(v1) WHERE v1.age > 32 RETURN v2

Boolean Operations

You can use the bit operators &, | as boolean operators AND and OR and the ! operator (in ruby < 1.9 use the not method)

Example:

n=node(3, 1)
(n[:age] < 30) & ((n[:name] == 'foo') | (n[:size] > n[:age]))
n

Which will generate: START v1=node(3,1) WHERE (v1.age < 30) and ((v1.name = \"foo\") or (v1.size > v1.age)) RETURN v1

Alternative, using the where method and a ruby block.

node(3,1).where{|n| (n[:name] == 'foo') | (n[:size] > n[:age]) } } 

Generates:

START v1=node(3,1) WHERE (v1.name = "foo") or (v1.size > v1.age) RETURN v1

Optional Properties

If a property does not exist in will raise an exception if it's used.

An example using a property (desc) which may not exist.

node(3,4)[:desc?] == 'hello'

Same as START v1=node(3,4) WHERE v1.desc? = "hello" RETURN v1

Checking if an property exists

Use the property? method.

Return only nodes which has property belt

node(3, 1).property?(:belt)

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

The p argument is the the node(:person) object.

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