Cypher: Shortest Path with Constraint

主宰稳场 提交于 2021-02-08 10:57:15

问题


I want to perform a shortest path query like the following:

START source=node:myIndex(name="<src>"), destination=node:myIndex(name = "<dst>")                                                                               
MATCH p = shortestPath(source-[:REL1*..5]-destination),
          source-[sourceRel:REL1]-m, 
          destination-[destRel:REL1]-k
WHERE sourceRel.a=<someValue> and destRel.a=<someOtherValue>                                                                                                      
RETURN NODES(p);

I want to get the shortest path between <src> and <dst> with the constraint that the property a has a certain value on the first relationship from src and dst respectively to the next node.

However, neo4j just returns any shortest path it finds without taking into account my constraint. What am I doing wrong? What is the correct way to specify constraints on the first "hop" of a shortest path for a shortest path query?

edit: I'm using Neo4j 1.8.2.


回答1:


As of 2.0.0-M03 there's no good way to introduce constraints to shortestPath. They are working on a new syntax to be able to do that, but it's still in the design phase. In order to do this, you'd need to take the less efficient route of not using shortestPath, order by length and get the shortest one that matches all your constraints.




回答2:


Now knowing what I want to do is not possible in the current Neo4j version (thanks Wes), I use a workaround to get this going. First I obtain both for the src and destination node the next node matching the constraint:

START n=node:myIndex(name="<nodename>")                             
MATCH n<-[rel:REL1]-m
WHERE rel.a=<somevalue>
RETURN m

Like this, I have the two node IDs of the "next" nodes of src and dst. I now use calculate the shortest path between those two node IDs and prepend the original source and append the original destination node to obtain the full path. It requires 3 queries instead of one but is probably not as expensive as the method Wes suggested.



来源:https://stackoverflow.com/questions/17631953/cypher-shortest-path-with-constraint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!