Search code examples
neo4jcypherneo4j-traversal-api

Traversing Neo4j graph in increasing order of relationship weights using Cypher


Consider I have following graph with edge weights:

enter image description here

I want to know if I can perform traversal starting at node a and following edges with increasing order of their weight using CYPHER. That is above it should return (a)-4->(e)-3->(c)-3->(d)

Is this possible using cypher?


Solution

  • Your description is slightly wrong (based on your example), as you don't want to traverse relationships with an increasing weight, you want to traverse the relationship(s) with the maximum weight at each step.

    You can't do it in a generic way in Cypher, because the result is built iteratively, and you can't know the maximum length of a result path.

    In Cypher, you'd have to

    1. build all the paths
    2. filter them by the weight of the first relationship
    3. filter the remaining ones by the weight of the second relationship (it if exists)
    4. etc.

    The declarative nature of Cypher is not really compatible: it would be cumbersome, and probably slow as well. It would be much easier to build a procedure or function (in the upcoming Neo4j 3.1) traversing the longest path(s), with the PathExpander only returning the relationships with the maximum weight from the current node.