Search code examples
neo4jcypher

Check the nodes having two relationships of type IS_TRUE


I am trying to fetch all nodes of type RULE having two relationships of type IS_TRUE or IS_FALSE from the same node. I can extract nodes with a single relationship like this:

MATCH (r:RULE)-[:IS_TRUE]->(n)

RETURN r

But I want to check those nodes that are producing two or more edges having an IS_TRUE relationship. The above query only returns all nodes that are producing IS_TRUE relationship.


Solution

  • This is probably the most efficient approach:

    MATCH (r:RULE)
    WHERE SIZE([(r)-[:IS_TRUE]->()|1]) = 2
    RETURN r
    

    This query's SIZE clause is constructed in such a way that it causes the Cypher query planner to use the getDegree operation, which does not need to hit the DB to get the number of relationships. Please read this other answer for the details.