Search code examples
neo4jcypher

Cypher query to find circular reference


Given the example found here: http://console.neo4j.org/?id=qzjrxu, how would I identify nodes with relationships that end back to the starting node?

IE: joe -> bill -> tom -> joe AND matt -> matt

Thanks for the help.


Solution

  • For small to medium graphs, this should return nodes suffering from a circular reference and the path itself:

    MATCH (e)
    WHERE SIZE((e)<-[:ManagedBy]-()) <> 0 
    AND SIZE(()<-[:ManagedBy]-(e)) <> 0
    MATCH path = (e)<-[:ManagedBy*]-(e) 
    RETURN e, path
    

    EDIT

    I made a small change to first filter out nodes which do not have incoming and outgoing :ManagedBy relationships, those will never have a cycle.

    Also it's highly recommended to use labels to reduce the nodes processed to the smallest set.