Hey Community!
I'm looking to create a Virtual Node which combines all the properties, inbound and outbound relationships of two nodes.
I've made a simplified dataset to illustrate my challenge:
CREATE (sub1:Sub {attr1: "1"})
CREATE (sub2:Sub {attr2: "2"})
CREATE (value1:Val {valueAttr1: "1"})
CREATE (value2:Val {valueAttr2: "2"})
CREATE (value3:Val {valueAttr3: "3"})
CREATE (vc1:VC)-[:subRel]->(sub1)-[:value]->(value1)
CREATE (vc2:VC)-[:subRel]->(sub2)-[:value]->(value2)
MERGE (vc1)-[:subRel]->(sub1)-[:value]->(value1)
MERGE (vc2)-[:subRel]->(sub2)-[:value]->(value2)
MERGE (sub2)-[:value]->(value3)
This is what I have been trying:
MATCH (n:Sub)
WITH collect(n) AS nodes
WITH apoc.map.mergeList([node IN nodes | apoc.any.properties(node)]) AS mergedProps, nodes
CALL apoc.create.vNode(['vSub', 'VirtualNode'], mergedProps) YIELD node AS virtualNode
WITH virtualNode, nodes
UNWIND nodes AS n
MATCH (n)-[rOut]->(relatedOutboundNode)
WITH virtualNode, n, nodes, rOut, relatedOutboundNode
CALL apoc.create.vRelationship(virtualNode, type(rOut), apoc.any.properties(rOut), relatedOutboundNode) YIELD rel AS vOutRel
WITH DISTINCT virtualNode, vOutRel, relatedOutboundNode, rOut, n, nodes
MATCH (n)<-[rIn]-(relatedInboundNode)
WITH virtualNode, rIn, relatedOutboundNode, nodes, relatedInboundNode, vOutRel, rOut
WHERE NOT (relatedInboundNode)-[:subRel]->(virtualNode)
CALL apoc.create.vRelationship(relatedInboundNode, type(rIn), apoc.any.properties(rIn), virtualNode) YIELD rel AS vInRel
RETURN virtualNode, rOut, rIn, relatedOutboundNode, nodes, vOutRel, relatedInboundNode, vInRel
My problem is that the two : Val
nodes makes my query duplicate the :subRel
relations. I need to "carry forward" (WITH
) the outbound relationships and nodes in order to have them part of the RETURN
, and that messes up my attempts to only make a unique virtual :subRel
.
Here's a screenshot with the virtual node highlighted in the middle:
I'm looking for a way to only have the one subRel
, corresponding to (vc2)-[:subRel]->(sub2)
, irrespective of how many :Val
nodes there are.
Any ideas how I can tweak my query will be super appreciated!
Nis