Showing results for 
Search instead for 
Did you mean: 

Head's Up! Site maintenance this Wednesday, February 1. Disruptions expected as we migrate the forums.

Get shortest path between nodes going via specific node


We have a Neo4J database that tracks people working for companies. The general structure is -


A person can have multiple jobs at the same time and each company can have multiple people.

Given 2 companies (Company 1 and Company 2) we can calculate the shortest path using -

match (start:Company {id:1}),(end:Company {id:2}), p = shortestPath((start)-[:WORKS_AT*]-(end)) return *

What we want to do, is calculate the shortest path between the 2 companies where the path includes specific people, e.g. -

(Company 1)-(Person 1)-(Company 4)-(Person 2)-(Company 2)

would be returned instead of the following if we wanted to connect via Person 2 -

(Company 1)-(Person 3)-(Company 2)



It sounds like you already have easy one-hop data on what companies the people you're interested work for. So find the shortest path between the people, not the companies, and then just do a query for what companies those people work for. For example something like:

MATCH (p1:Person { name: "Joe" })-[:WORKS_AT]->(c1:Company)
MATCH (p2:Person { name: "Sarah"})-[:WORKS_AT]->(c2:Company)
MATCH p=shortestPath((p1)-[*]-(p2))

Your shortest path is now p + the one hop on either side that connects p1 to c1, and p2 to c2