Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.
08-11-2021 04:09 AM
08-11-2021 05:54 AM
You could use a list comprehension, which is like using map
to transform an array of somethings into a an array of something else.
For example, modifying your example to use the movie graph:
MATCH (m:Movie {title:"The Matrix"}),(o:Person {name:"Tom Hanks"}),
p = shortestPath((m)-[*..15]-(o))
RETURN [x in nodes(p) | id(x)]
Best,
ABK
Reference: Lists - Neo4j Cypher Manual
08-11-2021 08:05 AM
Thank you abk,
I need one more help,
How to return their weight (distance) value in a list
08-11-2021 12:59 PM
I'm unsure what you mean by weight or distance. Is that a property on the nodes?
In general, you can pluck whatever you need to get from the object in the second part of the list comprehension, following the |
character.
Walking through the syntax of the list comprehension:
RETURN [x in nodes(p) | id(x)]
x in
means that x will receive a sequence of valuesnodes(p)
provides the sequence, which here will be the nodes of the path p
|
is a separator. The left-hand side of will "bind" values that are passed to the right-hand sideid(x)
could be any expression. Here we know x
is a node, so we're asking for that node's idSo, to get a property from the node instead, do this:
RETURN [x in nodes(p)) | x.name]
Does that help?
-ABK
08-11-2021 01:19 PM
weight(distance/cost) is a property Keys of the graph,
here I will explain a example:
CREATE (a:Location {name: 'A'}),
(b:Location {name: 'B'}),
(c:Location {name: 'C'}),
(h:Location {name: 'H'}),
(j:Location {name: 'J'}),
(a)-[:ROAD {cost: 50}]->(b),
(a)-[:ROAD {cost: 50}]->(c),
(c)-[:ROAD {cost: 40}]->(j),
(j)-[:ROAD {cost: 30}]->(h),
(h)-[:ROAD {cost: 50}]->(b);
Query
MATCH p=(o{name:"A"})-[r*]->(x{name:"B"})
RETURN [x in nodes(p) | id(x)]
path
expected output
path cost
1. [A,C,J,H,B] [0,50,90,130,180]
2. [A,B] [0,50]
Thank you in advance
08-11-2021 02:17 PM
OK, so you'd like to get values from the relationships rather than the nodes, and accumulate them along the way? That's more of a reduce/fold on an array which produces a new array, rather than a map function.
So let's try reduce:
RETURN reduce(costs=[0], x in relationships(p) | costs + [costs[size(costs) - 1] + x.cost])
0
p
to x
Though if you just want the total cost of the path you could simplify to:
RETURN reduce(total=0, x in relationships(p) | total + x.cost)
Closer?
Best,
ABK
ps. The cypher manual has a lot of good information about lists. Check out:
All the sessions of the conference are now available online