问题
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:
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
来源:https://stackoverflow.com/questions/48635710/how-to-do-relative-node-ordering-using-neo4j-cypher