arifainchtein
arifainchtein

Reputation: 11

rank nodes according to parameters of paths in Neo4J

I have 100 nodes, n1, n2, n3 etc which are connected by three different kind of relationships, r1,r2, and r3. Each of this relationships have a parameter called "weight" which is a number between lets say, 5, 10 and 15. I need to develop a ranking based on the number of total paths per node and also another ranking based on the weight. By total paths i mean that if N1-[r1]->n2 and n2-[r1]->n3 and n3-[r3]->n4 then the total number of paths for n1 would be 3. the value of the ranking by weight would be 5+5+15=25.

Ideally the query would return a list of the nodes ranked.

Is there a way to do that in cypher?

thanks

Upvotes: 1

Views: 687

Answers (2)

FrobberOfBits
FrobberOfBits

Reputation: 18002

Try this, of course with some tweaks for your data model:

MATCH path=(a:Foo)-[:r1|r2|r3*]->(d:Foo) 
RETURN length(path) as NumberOfStepsInPath, 
       reduce(sum=0, y in 
              extract(x in relationships(path) | x.weight) 
              | sum + y) 
       as TotalCost;

So this matches a path from a to d, on any of the relationship types you specify, r1|r2|r3. The length of the path is easy, that's just length(path). Summing the weights is a bit more involved. First, you extract the weight attribute from each relationship in the path. Then you reduce the list of weights down to a single sum.

Upvotes: 1

Michael Hunger
Michael Hunger

Reputation: 41676

Something like this??

MATCH (n1:Label {id:1})-[r1]->(n2:Label {id:2})-[r2]->(n3:Label {id:3})-[r3]->()
RETURN n1, 
      SUM(r1.weight+r2.weight+r3.weight) as weight, 
      count(*) as paths
ORDER BY weight desc, paths desc

Upvotes: 1

Related Questions