Reputation: 1940
I am trying to build up a subgraph from original graph , the scenario is given below
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
Reputation: 1304
Do you have something like this in mind?
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);
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.
╒═════════════════╤═════════════════╕
│"sourceNode" │"targetNode" │
╞═════════════════╪═════════════════╡
│{"name":"Node B"}│{"name":"Node C"}│
├─────────────────┼─────────────────┤
│{"name":"Node E"}│{"name":"Node F"}│
└─────────────────┴─────────────────┘
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);
Upvotes: 0