How to do relative node ordering using Neo4J Cypher?

假装没事ソ 提交于 2020-01-06 07:16:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!