I'm trying to find the lightest path from node a
to e
in the following graph:
The result should be 13:
a -> b: 1
b -> c: 3
c -> d: 4
d -> e: 5 (take lighter edge)
----------
13
I tried several examples, (eg https://neo4j.com/docs/graph-algorithms/current/algorithms/shortest-path/ ) but can't find the right query.
MATCH (start:LocationNode{name:'a'}), (end:LocationNode{name:'e'})
CALL algo.shortestPath(start, end, 'weight',{write:true,writeProperty:'sssp'})
YIELD writeMillis,loadMillis,nodeCount, totalCost
RETURN writeMillis,loadMillis,nodeCount,totalCost
results in
╒═════════════╤════════════╤═══════════╤═══════════╕
│"writeMillis"│"loadMillis"│"nodeCount"│"totalCost"│
╞═════════════╪════════════╪═══════════╪═══════════╡
│3 │3 │5 │12.0 │
└─────────────┴────────────┴───────────┴───────────┘
and
MATCH (start:LocationNode{name:'a'}), (end:LocationNode{name:'e'})
CALL algo.shortestPath(start, end, 'weight',{
nodeQuery:'MATCH(n:LocationNode) RETURN id(n) as id',
relationshipQuery:'MATCH(n:LocationNode)-[r:CONNECTED_TO]->(m:LocationNode) RETURN id(n) as source, id(m) as target, r.weight as weight',
graph:'cypher'})
YIELD writeMillis,loadMillis,nodeCount, totalCost
RETURN writeMillis,loadMillis,nodeCount,totalCost
results in
╒═════════════╤════════════╤═══════════╤═══════════╕
│"writeMillis"│"loadMillis"│"nodeCount"│"totalCost"│
╞═════════════╪════════════╪═══════════╪═══════════╡
│3 │19 │4 │14.0 │
└─────────────┴────────────┴───────────┴───────────┘
Other queries like the following don't even return anything:
MATCH p=(LocationNode{name:'a'})-[:CONNECTED_TO*]->(LocationNode{name:'e'})
RETURN p as shortestPath,
REDUCE(weight=0, r in relationships(p) | weight+r.weight) AS totalDistance
I would like to see a query that returns '13' as solution and ideally displays the chosen path like this:
How can I achieve this?
Thank you very much.
This query:
MATCH p=(a:LocationNode{name:'a'})-[:CONNECTED_TO*]->(e:LocationNode{name:'e'})
WITH p, REDUCE(s=0, r IN RELATIONSHIPS(p) | s + r.weight) AS totalWeight
RETURN p, totalWeight
ORDER BY totalWeight
LIMIT 1
Returns this result:
╒══════════════════════════════════════════════════════════════════════╤═════════════╕
│"p" │"totalWeight"│
╞══════════════════════════════════════════════════════════════════════╪═════════════╡
│[{"name":"a"},{"weight":1},{"name":"b"},{"name":"b"},{"weight":3},{"na│13 │
│me":"c"},{"name":"c"},{"weight":4},{"name":"d"},{"name":"d"},{"weight"│ │
│:5},{"name":"e"}] │ │
└──────────────────────────────────────────────────────────────────────┴─────────────┘
In the neo4j Browser, if you disable the Connect result nodes option (at the bottom of the Browser Settings pane, which you can display by clicking the gear icon in the left panel), then the visualization will be:
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.