Search code examples
neo4jcypher

How to MATCH nodes with with more than 1 of a specified relationship


I'm trying to find all Datum nodes in Neo4j where there is more than 1 of the GOLDSOURCEFEED relationships pointing to it. And I don't care what type of node has the relationship. Here's the base query just so you can see the node variables etc.

MATCH (p:Datum)<-[:GOLDSOURCEFEED]-()
WHERE exists ( (p:Datum)<-[:GOLDSOURCEFEED]-() )
RETURN p.name

Obviously when I put in the list above, I get all of the Datum nodes that have a GOLDSOURCEFEED relationship, I want to refine that to only list where there's more than one GOLDSOURCEFEED relationship.


Solution

  • You should use an efficient degreeness check:

    MATCH (p: Datum)
    WHERE SIZE((p)<-[:GOLDSOURCEFEED]-()) > 1 
    RETURN p.name;
    

    A degreeness check simply uses data already available for each node, and does not require actually getting the paths. It is possible to perform a degreeness check when you do not care about the node on the opposite end of the relationship or any relationship properties.

    [UPDATE]

    Starting with neo4j 5.0, you can use a COUNT subquery to do a degreeness check. For example:

    MATCH (p: Datum)
    WHERE COUNT{ (p)<-[:GOLDSOURCEFEED]-() } > 1 
    RETURN p.name;
    

    As above, this will get the degree for p without hitting the DB to if the pattern in the COUNT subquery leaves the other end of the relationship unspecified and does not specify any relationship properties.