Search code examples
neo4jcypher

cypher: query for a pattern and parts of a pattern


I am searching a collection for small subgraphs using cypher. I'm looking for the pattern A->B->C but I want to also see instances where A, B, or C are isolated and subsets of the pattern such as instances where the pattern is incomplete eg. A->B or B->C

I know I can get isolated nodes using the following for each node type

MATCH (a:A)
WHERE NOT EXISTS ((a)--())
RETURN a

and I can match my pattern with

MATCH (a:A)-[r1]->(b:B)-[r2]->(c:C)
RETURN a,b,c,r1,r2

How can I search for parts of the pattern where there is say, A->B but no follow on relation for B? Finding incomplete patterns is required.

Note: the database is in Neo4j and it is not a fully connected graph but rather a set of many independent small graphs, hence why I can find 'part' of a pattern.


Solution

  • If there are only three nodes, then below will give you all subsets of the pattern (A)-(B)-(C). That is, isolated node A, B, C, connected A-B, B-C and A-C.

    MATCH (p) WHERE NOT EXISTS ((p)--()) and labels(p) in [['A'], ['B'], ['C']]
    RETURN p
    UNION ALL
    MATCH p=(:A)--(b:B) WHERE NOT EXISTS ((b)--(:C))
    RETURN p
    UNION ALL
    MATCH p=(b:B)--(:C) WHERE NOT EXISTS ((:A)--(b))
    RETURN p
    UNION ALL
    MATCH p=(:A)--(:C) 
    RETURN p
    

    Sample Data:

    enter image description here

    CREATE (a1:A {title: "a1"})
    CREATE (a2:A {title: "a2"})
    CREATE (a3:A {title: "a3"})
    CREATE (b1:B {title: "b1"})
    CREATE (b2:B {title: "b2"})
    CREATE (b3:B {title: "b3"})
    CREATE (c1:C {title: "c1"})
    CREATE (c2:C {title: "c2"})
    CREATE (c3:C {title: "c3"})
    CREATE (a1)-[:LINKS]->(b1)
    CREATE (b2)-[:LINKS]->(c2) 
    CREATE (a3)-[:LINKS]->(b3)-[:LINKS]->(c3); 
    

    Result:

    enter image description here