neo4j 最短路径 java,如何在Neo4j中找到跳数最少的最短路径?

Im modeling a graph where nodes are places and edges indicate that you can go from one place to another.

This is to have all routes that you can take from a place to another,

and you can go from a place to another by different routes, so I want a query that returns me the shortest path with the minimum route changes.

For example, I want to go from A to D, I have two possible paths:

(place {name: "A"})-[:FOLLOWS{route:""R1}]->(place{name: "B" })-[:FOLLOWS{route:""R4}]->(place{name:"C"})-[:FOLLOWS{route:""R2}]->(place{name:"D"})

(place {name: "A"})-[:FOLLOWS{route:""R1}]->(place{name: "B" })-[:FOLLOWS{route:""R1}]->(place{name:"F"})-[:FOLLOWS{route:""R2}]->(place{name:"D"})

In the previous two path, both are the same size, but I would like to get the second one, which is the one who has the minimum route changes.

Thank you.

解决方案

I think this will meet your needs. It finds all of the shortest paths. Then it processes each one to count the number of route changes. It then orders the result set by the fewest route changes and limits the result set to the first occurrence.

// find all of the shortest paths that match the beginning and ending nodes

match p=allShortestPaths((a:Place {name: 'A'})-[:FOLLOWS*]->(d:Place {name: 'D'}))

// carry forward the path, the relationships in the path and a range that represents the second to last relationships in the path

with p,relationships(p) as rel, range(1,length(p)-1) as index

// use reduce to process the route attribute on the relationship to accumulate the changes

with p, rel, index, reduce (num_chg = 0, i in index | num_chg +

case when (rel[i]).route = (rel[i-1]).route then 0 else 1 end ) as changes

// return the path and the number of route changes

return p, changes

// only return the path with the fewest route change

order by changes

limit 1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值