Calculating from relationships in a multi-node path

I have a non-cyclical graph, where all the nodes are of type (label) Entity and all relationships are of type OWNS. Each relationship is guaranteed to have a property Percentage, which is the numeric data type. Each node has an Id field (different from the internal id that Neo4j uses).

Given a starting node and target node, the path between them can have 1 relationship or many in between (if there are many nodes in that path). Using Cyper, how can I return the total percentage between the starting and target node? This can be complicated because the paths aren’t always linear. I’ve attached a picture example below.

I only started using Neo4j a week ago, so this is the very simplistic query I’ve written just to show the nodes and relationships given a starting and target node:

MATCH p=(:Entity {Id: "<STARTING ID>"})-[:OWNS*]->(:Entity {Id: "<TARGET ID>"})
RETURN p

However, instead of showing the graph, I would just like the calculated percentage between them.

Example:

I think for this case you would calculate the percentage per path, then add the result together for all paths.

The Cypher would look like this, assuming id 1 for the start, and id 5 for the end, and percentage as the floating point numeric percentage on each :OWNS relationship:

WITH 1 as startId, 5 as endId
MATCH path = (start:Entity {id:startId})-[:OWNS*]->(end:Entity {id:endId})
WITH reduce(total=1.0, rel IN relationships(path) | total * rel.percentage) as pathOwnership
RETURN sum(pathOwnership) as totalOwnershipPercentage

Recreating your sample graph, this finds 2 paths and the result of the query is 0.24800000000000003 which should match with your expectations.

1 Like