简体   繁体   中英

Find shortest path between two nodes with all relationships having the same property value

Consider the following graph:

A --p1--> B --p1--> C --p1--> D
          |                   ^
          '--------p2---------'

A, B, C, D are nodes and all relationships have an integer property pid (values: p1, p2, ... pn) that are used to identify a path.

Q: How can I find the shortest path between A and D with only a single path id?


I can query for an absolute value with:

MATCH (w1 {name:"A"}), 
      (w2 {name:"D"}), 
      p = shortestPath((w1)-[:N*]->(w2))
WHERE all(r IN relationships(p) WHERE r.pid=3) 
RETURN p;`

But pid can be any value that I do not know beforehand (and do not care about). I only care about the fact that pid should be the same for all relationships. Something like this:

MATCH (w1 {name:"A"}), 
      (w2 {name:"D"}), 
      p = shortestPath((w1)-[:N*]->(w2))
WHERE all(r IN relationships(p) WHERE r.pid = relationships(p)[0].pid ) 
RETURN p;`

Ideally you would want the shortest path algorithm itself to check that each relationship in the path has the same value for x , but alternatively you can go one relationship out from your start node and check that the shortest path shares an x value with that first relationship. This will give you one shortest path per neighbor to w1 and you can then return the shortest of those.

MATCH (w1 {name:"A"})
MATCH (w2 {name:"D"})
WITH w1, w2
MATCH (w1)-[first_rel:N]->()
p = shortestPath((w1)-[:N*]->(w2))
WHERE all(r IN relationships(p) WHERE r.x=first_rel.x) 
RETURN p, size(p) AS sz ORDER BY sz LIMIT 1

What about this?

Set parameters for key and value eg to 'myField' and 'myValue'

And then

MATCH (w1 {name:"A"}), 
      (w2 {name:"D"}), 
      p = shortestPath((w1)-[:N*]->(w2))
WHERE all(r IN relationships(p) WHERE r[$key]=$value)
RETURN p;

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