subhanshu kumar
subhanshu kumar

Reputation: 392

how to find the shortest relationship between the two nodes in neo4j?

I have multiple relationships in my graph. I wanted to find the shortest relationship between the two nodes.

I have two types of nodes: 1.person 2.Company

and many relationships between those nodes such as phone, email, address, etc.

Here is the screenshot of my graph

I tried doing:
MATCH (r)-[q:*1..3]-(p) return type(q)
But it gave an error message:

Invalid input '*': expected whitespace or a rel type name (line 1, column 14 (offset: 13))

I also tried MATCH (r)-[*]-(p) return * but it is taking the infinite time. I also tried the query via indexing to fasten the process but still no luck.

Please let me know how to find the shortest path between the nodes.

Upvotes: 3

Views: 450

Answers (2)

Dave Bennett
Dave Bennett

Reputation: 11216

Have you consulted the Neo4j Cypher Manual per chance on shortestPath?

https://neo4j.com/docs/cypher-manual/current/clauses/match/#query-shortest-path

If you wanted to find the shortest path...

MATCH path=shortestPath((r:person {name: 'Sandeep Garg'})-[q*1..3]-(p:Company {name: 'Gopal Prjapati'}))  
RETURN path

If you wanted to find the realtionships in the shortest path

MATCH path=shortestPath((r:person {name: 'Sandeep Garg'})-[q*1..3]-(p:Company {name: 'Gopal Prjapati'}))  
RETURN realtionships(path)

Upvotes: 1

cybersam
cybersam

Reputation: 66957

There were 2 errors in this query:

MATCH (r)-[q:*1..3]-(p)  return type(q)
  1. The colon (":") should only be used in a relationship pattern in front of a type name. Since in your case you did not want to specify a type name, you need to omit the colon.
  2. Since q is used in a variable-length path pattern, its value will be a list of relationships.

Here is a query that should actually return what your query seemed to be attempting to return:

MATCH ()-[qs*..3]-()
UNWIND qs AS q
RETURN TYPE(q)

Now, if you want to find the shortest path between 2 nodes (as indicated by your question subject), see @DaveBennett's answer (assuming he fixes the issues I mentioned in a comment to his answer).

Upvotes: 4

Related Questions