# Get shortest path between nodes going via specific node

**URL:** <https://community.neo4j.com/t/get-shortest-path-between-nodes-going-via-specific-node/28883>\
**Category:** Cypher\
**Tags:** cypher, shortest-path\
**Created:** [November 12, 2020, 9:14am UTC](https://community.neo4j.com/t/get-shortest-path-between-nodes-going-via-specific-node/28883 "2020-11-12T09:14:49Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![andyking27](https://sea1.discourse-cdn.com/flex021/user_avatar/community.neo4j.com/andyking27/32/4113_2.png) [@andyking27](https://community.neo4j.com/u/andyking27)\
**Post date:** [November 12, 2020, 9:14am UTC](https://community.neo4j.com/t/get-shortest-path-between-nodes-going-via-specific-node/28883/1 "2020-11-12T09:14:49Z")

</div>

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

`(Person)-[:WORKS_AT]->(Company)`

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

---

<div class="post-metadata">

**Author:** ![david\_allen](https://sea1.discourse-cdn.com/flex021/user_avatar/community.neo4j.com/david_allen/32/13090_2.png) [@david\_allen](https://community.neo4j.com/u/david_allen)\
**Post date:** [November 12, 2020, 12:15pm UTC](https://community.neo4j.com/t/get-shortest-path-between-nodes-going-via-specific-node/28883/2 "2020-11-12T12:15:59Z")

</div>

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:

```auto
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
