Search code examples
graphneo4jcyphersubgraph

Get all subgraphs of a particular type in Neo4J


I have a set of nodes and relationships and I want to get subgraph of a particular type for a node. To explain the question, attached the image for the graph.

![enter image description here

Nodes in yellow are connected by nodes in green by a relation "IS_PART_OF". When we look at the above fragment, yellow node "8366854" is connected by 4 green nodes "P10398", "P10398-2", "A0A024" and "P02647" where yellow node "8366931" is connected by 2 green nodes "A0A024" and "P02647". So green nodes "A0A024" and "P02647" are common to both and I could say yellow node "8366931" is a sub of "8366854". This happens only if all green nodes are common to both.

So my query will be a yellow node id say "8366854", which returns all sub yellow nodes (in this case only "8366931").

So in this way for the below fragment, I could say,

1) "8366523" is sub of "8366848"

2) "8366915" not a sub of "8366848" since it doesn't have all green nodes in common.


Solution

  • Actually, the cypher allows you to express this by a sequence of instructions:

    • take the yellow node and take all his green neighbors
    • for each green neighbor to find the yellow and its green neighbors
    • make sure that for the second yellow neighbor, each green neighbor is also the neighbor of the first yellow node

    MATCH (Y1:YELLOW)<-[:IS_PART_OF]-(G:GREEN)
    WITH Y1, 
         collect(G) AS greens1
    UNWIND greens1 AS G
    MATCH (G)-[:IS_PART_OF]->(Y2:YELLOW)<-[:IS_PART_OF]-(G2:GREEN) WHERE Y1 <> Y2
    WITH Y1, Y2, greens1, 
         collect(G2) AS greens2 
         WHERE SIZE(greens1) > size(greens2) AND 
               ALL(G IN greens2 WHERE G IN greens1)
    RETURN Y1, collect(Y2) AS subs