Neo4j::Cypher Examples

Alex Burkhart edited this page Jul 1, 2013 · 5 revisions
Clone this wiki locally

Example 1:

Cypher

START v1=node(3)
MATCH v2 = (v1)-[:`r`]->(x)
RETURN v2

Ruby

node(3) > :r > :x

Example 2:

Cypher

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

Ruby

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

Example 3:

Cypher

START v2=node(1)
MATCH (v2)-[v1:`friends`]->(v3)
WHERE (v1.since = 1994)
RETURN v3

Ruby

node(1).outgoing(rel(:friends).where{|r| r[:since] == 1994})

Example 4:

Cypher

START v1=node(2,3,4,1)
RETURN count(v1.property?)

Ruby

node(2, 3, 4, 1)[:property?].count

Example 5:

Cypher

START v1=node(42)
MATCH (v1)-[:`favorite`]->(stuff)<-[:`favorite`]-(person)
WHERE not((v1)-[:`friend`]-(person))
RETURN person.name,count(stuff)
ORDER BY count(stuff) DESC

Ruby

node(42).where_not { |m| m - :friend - :person } > :favorite > :stuff < :favorite < :person
ret(node(:person)[:name], count(:stuff).desc)

Example 6:

Cypher

START n=node(42)
MATCH (n)-[r]->(m)
WITH n,collect(type(r)) as out_types,collect(m) as outgoing
MATCH (n)<-[r]-(m)
RETURN n,outgoing,out_types,collect(m) as incoming,collect(type(r)) as in_types"

Ruby

n = node(42).as(:n)
r = rel('r')
m = node(:m)
rel_types = r.rel_type.collect
end_nodes = m.collect

n.with_match(rel_types.as(:out_types), end_nodes.as(:outgoing)) { |n, _, _| n < r < m } > r > m

ret(n,
    :outgoing,
    :out_types,
    end_nodes.as(:incoming),
    rel_types.as(:in_types))

Example 7:

Co-Tagged Places - Places Related through Tags.

Find places that are tagged with the same tags: Determine the tags for place x. What else is tagged the same as x that is not x."

Cypher

START place=node:node_auto_index(name = "CoffeeShop1")
MATCH place-[:tagged]->tag<-[:tagged]-otherPlace
RETURN otherPlace.name, collect(tag.name)
ORDER By otherPlace.name desc

Ruby

other_place = node(:otherPlace)
place = lookup('node_auto_index', 'name', 'CoffeeShop1').as(:place)
place > rel(':tagged') > node(:tag) < rel(':tagged') < other_place
ret other_place[:name].desc, node(:tag)[:name].collect

Or in one line:

  lookup('node_auto_index', 'name', 'CoffeeShop1') > rel(':tagged') > node(:tag).ret { |t| t[:name].collect } < rel(':tagged') < node(:otherPlace).ret { |n| n[:name].desc }