Mauro Scarpa
Mauro Scarpa

Reputation: 51

Find the distance in a path between each node and the last node of the path

I am very new to Cypher and I need help to solve a problem I am facing.. In my graph I have a path represeting a data stream and I need to know, for each node in the path, the distance from the last node of the path. For example if i have the following path:

(a)->(b)->(c)->(d)

the distance must be 3 for a, 2 for b, 1 for c and 0 for d. Is there an efficient way to obtain this result in Cypher? Thanks a lot!

Mauro

Upvotes: 1

Views: 1522

Answers (2)

Dave Bennett
Dave Bennett

Reputation: 11216

If it is just hops between nodes then i think this will fit the bill.

match p=(a:Test {name: 'A'})-[r*3]->(d:Test {name: 'D'}) 
with p, range(length(p),0,-1) as idx
unwind idx as elem
return (nodes(p)[elem]).name as Node
, length(p) - elem as Distance
order by Node

Upvotes: 2

cybersam
cybersam

Reputation: 66999

In this answer, I define a path to be "complete" if its start node has no incoming relationship and its end node has no outgoing relationship.

This query returns, for each "complete" path, a collection of objects containing each node's neo4j-generated ID and the number of hops to the end of that path:

MATCH p=(x)-[*]->(y)
WHERE (NOT ()-->(x)) AND (NOT (y)-->())
WITH NODES(p) AS np, LENGTH(p) AS lp
RETURN EXTRACT(i IN RANGE(0, lp, 1) | {id: ID(np[i]), hops: lp - i})

NOTE: Matching with [*] will be costly with large graphs, so you may need to limit the maximum hop value. For example, use [*..4] instead to limit the max hop value to 4.

Also, qualifying the query with appropriate node labels and relationship types may speed it up.

Upvotes: 1

Related Questions