Skip to content

Neo4j::Cypher Examples

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

Examples

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

  node(3) > :r > :x

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

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

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

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

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

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

"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"

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

== Complex Example

"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"

    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)])

=== 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."

"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"

Can be written like this:

    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
  end

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 }
Clone this wiki locally