Kalyan
Kalyan

Reputation: 1940

Facing problem generating subgraph from original graph in neo4j and networkX

I am trying to build up a subgraph from original graph , the scenario is given below

enter image description here

Here nodes b and C are connected with node A. My desired output is if two nodes are connected with a common node then they are connected. How can I solve this with neo4j or networkX? My focus is on neo4j for cypher query but they have networkX binding as well. I am using python for developing this solution.

Upvotes: 1

Views: 91

Answers (1)

ThirstForKnowledge
ThirstForKnowledge

Reputation: 1304

Do you have something like this in mind?

1. Creating your model

For the ease of possible further answers and solutions I note my graph creating statement:

CREATE
    (nodeA:Node {name:'Node A'}),
    (nodeB:Node {name:'Node B'}),
    (nodeC:Node {name:'Node C'}),
    (nodeD:Node {name:'Node D'}),
    (nodeE:Node {name:'Node E'}),
    (nodeF:Node {name:'Node F'}),
    (nodeA)-[:CONNECTED]->(nodeB),
    (nodeA)-[:CONNECTED]->(nodeC),
    (nodeC)-[:CONNECTED]->(nodeD),
    (nodeD)-[:CONNECTED]->(nodeE),
    (nodeD)-[:CONNECTED]->(nodeF);

initial situation graph

2. Variant I (not graph changing)

2.1 Solution

MATCH
    path = (sourceNode:Node)<-[:CONNECTED]-(:Node)-[:CONNECTED]->(targetNode:Node)
WHERE
    id(sourceNode)<id(targetNode)
RETURN
    sourceNode, targetNode;

The second line describes your two-nodes-with-a-common-node-between pattern, while line four filters the resulting pairs for one direction only.

2.2 Result

╒═════════════════╤═════════════════╕
│"sourceNode"     │"targetNode"     │
╞═════════════════╪═════════════════╡
│{"name":"Node B"}│{"name":"Node C"}│
├─────────────────┼─────────────────┤
│{"name":"Node E"}│{"name":"Node F"}│
└─────────────────┴─────────────────┘

 

3. Variant II (graph extending)

3.1 Solution

The following Cypher query enrich your existing graph by direct relationships (NEW_CONNECTED) between depended nodes.

MATCH
    path = (sourceNode:Node)<-[:CONNECTED]-(:Node)-[:CONNECTED]->(targetNode:Node)
WHERE
    id(sourceNode)<id(targetNode)
MERGE 
    (sourceNode)<-[:NEW_CONNECTED]-(targetNode);

3.2 Result

resulting graph

Upvotes: 0

Related Questions