Neo4j::Cypher Where

Alex Burkhart edited this page Jun 26, 2013 · 11 revisions
Clone this wiki locally

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(itemA, itemB) {|a, b|
  ret a[:age], b[:age], (a[:age] - b[:age]).abs.as(:diff)
}

Same as:

START n0=node(3), n1=node(2)
RETURN n0.age, n1.age, abs(n0.age - n1.age) as diff

The IN operator.

To check if an element exists in a collection, you can use the IN operator. Example:

node(3, 1, 2)[:name].in?(["Peter", "Tobias"])

Generates

START v1=node(3,1,2)
WHERE (v1.name IN ["Peter","Tobias"])
RETURN v1