简体   繁体   中英

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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM