Tharik Kanaka
Tharik Kanaka

Reputation: 2510

How to retrieve nodes for multiple depth relationships Neo4j Database Cypher?

Assuming that there is a simple graph as follows,

(City {name:gotham})<-[:LOCATED]-(Tower {name:abc})<-[:LOCATED]-(Bank:{name:CityBank})
(City {name:gotham})<-[:LOCATED]-(Cinema {name:MainHall})
(City {name:gotham})<-[:LOCATED]-(Bank {name:ComBank})

How can i get all banks located in City named Gotham in Neo4j Database (including CityBank and comBank)? I tried following pattern, it returned all the nodes LOCATED in City named gotham (Including Cinema as well)

MATCH (City{name:'Gotham'})<--(Bank) RETURN Bank

Upvotes: 6

Views: 8214

Answers (1)

JohnMark13
JohnMark13

Reputation: 3749

Assuming you just mistyped the query, what isn't working?

MATCH (:City{name:'Gotham'})<--(bank:Bank) RETURN bank

should work fine.

Completely wrong as typed, should have read (the lonely star indicating, all relationships of any type, any length path):

MATCH (:City{name:'Gotham'})<-[*]-(bank:Bank) RETURN bank

Better would be:

MATCH (:City{name:'Gotham'})<-[:LOCATED*1..2]-(bank:Bank) RETURN bank

So as only to traverse LOCATED relationships. You can adjust the *1..2 (match paths of length 1 to 2) to meet path length requirements (if for example you added a Street or Block node, you might want to match paths up to length 3 *1..3)

Upvotes: 7

Related Questions