0
votes

I'm building a Maven dependency graph using Neo4J. One of the queries I need to support is finding all nodes that depend on a particular dependency. So if C depends on B and A, and B depends on A, findByDependency(A) should return B and C. I implemented this using the following query, and it's working:

MATCH (v1)-[:DEPENDS_ON]->(v2)
WHERE EXISTS (v1.gav) AND v2.gav = "A"
RETURN DISTINCT v1.gav

However, in my example above, C also depends on B in addition to depending on A. I'd like the result set to be sorted such that B comes before C. I can do this in code, but is there a way to do it using Cypher?

1
Are circular dependencies possible (e.g. if B depended on C as well as A)? If so, then there would be no single ordering.cybersam
@cybersam Circular dependencies are not allowed.Abhijit Sarkar

1 Answers

1
votes

If I understood correctly, then you need to calculate the interdependence of the nodes:

MATCH (v1)-[:DEPENDS_ON]->(v2 {gav: 'A'}) WHERE EXISTS(v1.gav)
OPTIONAL MATCH (v1)<-[:DEPENDS_ON]-(v3)-[:DEPENDS_ON]->(v2) WHERE EXISTS(v3.gav)
WITH DISTINCT v1.gav AS gav, 
     COUNT(v3) AS sortValue
RETURN gav 
ORDER BY sortValue DESC

Update: Another way:

MATCH p = (v1)-[:DEPENDS_ON*1..2]->(v2 {gav: 'A'}) 
    WHERE ALL(n IN NODES(p)[0..-1] WHERE EXISTS(n.gav))
WITH DISTINCT v1.gav AS gav, 
     SUM(LENGTH(p)) AS sortValue
RETURN gav 
ORDER BY sortValue ASC