Jhonathan
Jhonathan

Reputation: 330

ShortestPath with 3 or more nodes

I'm trying to execute a Cypher Query with Neo4J. I already execute a Shortest path beetween 2 nodes, but I'm want to know if is possible to execute with more nodes.

Ex with 2 nodes:

MATCH (personA:Person { contactId: 1000073595058 }),(personB:Person { contactId: 1000295524418 }), p = shortestPath((personA)-[*..30]-(personB)) RETURN p 

Ex with 3 nodes:

MATCH (personA:Person { contactId: 1000073595058 }),(personB:Person { contactId: 1000295524418 }),(personC:Person { contactId: 1000331998948 }), p = shortestPath((personA)-[*..30]-(personB)-[*..30]-(personC)) RETURN p 

But when I execute returns a exception. How can I do this?

Upvotes: 1

Views: 863

Answers (1)

Martin Preusse
Martin Preusse

Reputation: 9369

You can only MATCH a shotestPath between two nodes. You have to split up your query:

MATCH (personA:Person { contactId: 1000073595058 }),
      (personB:Person { contactId: 1000295524418 }),
      (personC:Person { contactId: 1000331998948 })
WITH personA, personB, personC
MATCH p = shortestPath((personA)-[..30]-(personB)
MATCH p2 = shortestPath((personB)-[..30]-(personC)
RETURN p, p2

Depending on what you want to do with the results, you can use aggregation functions to e.g. get all nodes from both paths:

...
RETURN nodes(p)+nodes(p2)

Upvotes: 2

Related Questions