Cypher Query create multi relations

107 Views Asked by At

I am trying to create a generic query for creating relations between nodes. The problem is when one match fail the other are ignored. The following query should create 3 relations. But it didn’t only 2. Thank you very much for your help. I am a beginer with Cypher Vince

MATCH (a:Strata),(b) WHERE a.uid = 'strata60' AND b.uid= 'cmCharacteristic' CREATE (a)-[r:IS_CONSTITUTED_BY]->(b)

 WITH 1 as dummy 

 MATCH (a:Strata),(b) WHERE a.uid = 'strata60' AND b.uid= 'cloudCharacteristic' CREATE (a)-[r:IS_CONSTITUTED_BY]->(b) 

WITH 1 as dummy 

 MATCH (a:Strata),(b) WHERE a.uid = 'strata60' AND b.uid= '' CREATE (a)-[r:IS_CONSTITUTED_BY]->(b) 

WITH 1 as dummy 


 MATCH (a:Strata),(b) WHERE a.uid = 'strata60' AND b.uid= '' CREATE (a)-[r:IS_CONSTITUTED_BY]->(b) 

WITH 1 as dummy 

 MATCH (a:Strata),(b) WHERE a.uid = 'strata60' AND b.uid= 'mFeCharacteristic' CREATE (a)-[r:IS_CONSTITUTED_BY]->(b)

 WITH 1 as dummy 

 MATCH (a:Strata),(b) WHERE a.uid = 'strata60' AND b.uid= '' CREATE (a)-[r:IS_CONSTITUTED_BY]->(b)
2

There are 2 best solutions below

0
On

A more generic query

match (a:Strata {uid: 'strata60'}), b where b.uid in ['x', 'cmCharacteristic']
with a, collect(b) as bs
foreach (b in bs | create unique a-[:REL]->b)

This will match only the b nodes which have a valid uid in the array given, and create a relation to each of them, so this will not fail if invalid uids are in the list (they'll just be ignored).

The query will run if there is at least one valid b; else it will fail, which is ok, since no relation should be created anyway.

0
On

You could use OPTIONAL MATCH instead of MATCH on all subsequent ones. Then if those ones don't exist your query won't fail.