cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Create if possible

So, I have this (simplified) query that creates a board with a relationship to a group.

MATCH (g:Group) CREATE (g)-[:ChildBoard]->(b:Board);

Now, if there already is a board with this relationship, I want to remove that relationship and create a new, different one.
(same g as above)

MATCH (g)-[oldRel:ChildBoard]->(oldBoard:Board) DELETE oldRel CREATE (b)-[:Sibling]->(oldBoard);

I'm trying to figure out how I'd do this, preferably in one query.
This is what I've got so far:

MATCH (g:Group) OPTIONAL MATCH (g)-[oldRel:ChildBoard]->(oldBoard:Board) DELETE oldRel CREATE (g)-[:ChildBoard]->(b:Board) CREATE (b)-[:Sibling]->(oldBoard);

The problem is, when oldBoard is null, it fails. I want it to simply not create it. I know there's a setting that makes it not throw an error in situations like these, but I'd like to know if there's a better way to do it.

1 REPLY 1

What about using COLLECT and UNWIND? Query the information you and and collect it into a list and then loop through the list and do what you need?

I haven't tried this so there's probably syntax errors but would something like this work for you?

MATCH (g:Group)

OPTIONAL MATCH (g)-[r:CholdBoard]->(oldBoard:Board)

WITH g, COLLECT(r) AS old_rels, COLLECT(oldBoard) AS old_boards

UNWIND old_boards AS x

CREATE (g)-[:Sibling]->(x)

WITH g, old_rels

UNWIND old_rels AS y

DELETE y