Skip to content

Neo4j::Cypher Examples

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

Examples

Example 5.2. Basic Friend finding based on social neighborhood

See http://docs.neo4j.org/chunked/snapshot/cypher-cookbook-friend-finding.html Let say we want to express the following Cypher Query:

START joe=node(some node id)
MATCH joe-[:knows]->friend-[:knows]->friend_of_friend, joe-[r?:knows]->friend_of_friend
WHERE r IS NULL
RETURN friend_of_friend.name, COUNT(*)
ORDER BY COUNT(*) DESC, friend_of_friend.name

This can be done like this:

Neo4j.query(joe_node) do |joe|
  friends_of_friends = node(:friends_of_friends)
  joe > ':knows' > node(:friend) > ':knows' > friends_of_friends
  r = rel('r?:knows')
  joe > r > friends_of_friends
  r.exist?
  ret(friends_of_friends[:name], count).desc(count).asc(friends_of_friends[:name])
end

Or like this using the outgoing instead of the > operator

Neo4j.query(joe_node) do |joe|
 friends_of_friends = joe.outgoing(:knows).outgoing(:knows)
 r = rel('r?:knows').as(:r)
 joe > r > friends_of_friends
 r.exist?
 ret(friends_of_friends[:name], count).desc(count).asc(friends_of_friends[:name])
end

Example 5.4. Find people based on similar favorites

Neo4j.query(me_node) do |me|
  me.where_not { |m| m - ':friend' - :person } > ':favorite' > :stuff < ':favorite' < :person
  ret(node(:person)[:name], count(:stuff).desc(count(:stuff)))
end

Is generates the following cypher string:

START n0=node(42) MATCH (n0)-[:favorite]->(stuff)<-[:favorite]-(person) WHERE not((n0)-[:friend]-(person)) RETURN person.name,count(stuff) ORDER BY count(stuff) DESC
Clone this wiki locally