如何在有向网中用cypher语言 按照关系上的权重属性 查询最短路径
发布于 1 年前 作者 sxjjames 1598 次浏览 来自 问答

IMG_20180521_155639.jpg 如图所示,如何用cypher查从B到D的最短路径? shortestpath() 是不行的,因为那个只能查没有权值的。

7 回复

自顶。学生党,做的毕设。老师不让用java

shortestpath()方法只能查 关系的“跳数”最少的路径,要按照自己权重查最优路径,就遍历全部路径,然后用reduce()方法筛选 比如下列方法不能用:

MATCH (start:Point {title: ‘Some Point 1’}), (end:Point {title: ‘Some Point 5’}) MATCH p=shortestPath((start)-[:distance*]->(end)) RETURN p

替换方法可以为:

MATCH (start:Point {title: ‘Some Point 1’}), (end:Point {title: ‘Some Point 5’}) MATCH p=(start)-[:distance*]->(end) WITH p,reduce(s = 0, r IN rels( p) | s + r.value) AS dist RETURN p, dist ORDER BY dist DESC

或者可以采用 APOC

MATCH (start:Point {title: ‘Some Point 1’}), (end:Point {title: ‘Some Point 5’}) CALL apoc.algo.dijkstra(start, end, ‘distance’, ‘value’) YIELD path, weight RETURN path, weight

match (d19:device{id:“19”}),(d20:device{id:“20”}),p=((d19)-[*1…10]->(d20)) with reduce(tot = 0, n IN rels§| tot + n.RC) AS ref, p return p order by ref asc limit 1

二楼的稍微有点问题,应该加个return就OK了。

针对主楼发的那个图,Cypher语言如下。 创建节点 Create(b:device{id:‘B’,name:‘X62W’,X:4,Y:10}) Create(e:device{id:‘E’,name:‘X62W’,X:18,Y:10}) Create(c:device{id:‘C’,name:‘X62W’,X:24,Y:10}) Create(d:device{id:‘D’,name:‘X62W’,X:40,Y:10}) Create(a:device{id:‘A’,name:‘X62W’,X:36,Y:5})

添加关系 match(b:device{id:‘B’,name:‘X62W’,X:4,Y:10}) match(e:device{id:‘E’,name:‘X62W’,X:18,Y:10}) match(c:device{id:‘C’,name:‘X62W’,X:24,Y:10}) match(d:device{id:‘D’,name:‘X62W’,X:40,Y:10}) match(a:device{id:‘A’,name:‘X62W’,X:36,Y:5}) create (b)-[:to{RC:14}]->(e) create (e)-[:to{RC:14}]->(b) create (e)-[:to{RC:6}]->© create ©-[:to{RC:6}]->(e) create ©-[:to{RC:16}]->(d) create (d)-[:to{RC:16}]->© create (d)-[:to{RC:9}]->(a) create (a)-[:to{RC:9}]->(d) create (a)-[:to{RC:37}]->(b) create (b)-[:to{RC:37}]->(a)

查询B节点到D节点的最短路径 match (b:device{id:“B”}),(d:device{id:“D”}),p=((b)-[*1…10]->(d)) with reduce(tot = 0, n IN rels§| tot + n.RC) AS ref, p return p order by ref asc limit 1

回到顶部