Search code examples
databaseneo4jcypheroverlapping

How to select specific overlapping pattern using Cypher?


I have a dataset with nodes and relationships in Neo4j. Something like this:

(a)-[r:sel]-(x)
(a)-[r:sel]-(y)
(a)-[r:sel]-(z)
(a)-[r:sel]-(w)
(b)-[r:sel]-(z) 
(b)-[r:sel]-(y)
(c)-[r:sel]-(z)

Nodes x,y,z and w have the label DEP with properties (ex: DEP.type). y and z have the same property (DEP.type are defined equally).

I would like select just nodes such as (b) but not nodes such as (a).
In other words, the nodes only in area written below:

Overlapping

Does anyone have any suggestions? Best wishes,


Solution

  • Scenario 1

    This query returns a collection of all the nodes that have a sel relationship with a, if and only if the collection has multiple nodes and all of them have the same type value.

    MATCH (a)-[r:sel]-(x)
    WITH a, COLLECT(x) AS col, LENGTH(COLLECT(DISTINCT x.type)) AS numTypes 
    WHERE numTypes = 1 AND LENGTH(col) > 1
    RETURN a, col;
    

    Scenario 2

    This query returns a collection of all the nodes that have a sel relationship with a, if and only if the collection has multiple nodes and the entire collection has a specified property with a specified value (in this example, type = foo).

    MATCH (a)-[r:sel]-(x)
    WHERE x.type = 'foo'
    WITH a, COLLECT(x) AS col
    WHERE LENGTH(col) > 1
    RETURN a, col;