Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Neo4J Cypher: Ensuring constraints exist (avoiding errors if they already do)

Tags:

neo4j

cypher

On app startup I'd like to ensure indicies and constraints exist.

When I call the following on app startup, I'm receiving an error as the constraint already exists:

CREATE CONSTRAINT ON (node:MyLabel) ASSERT node.myProperty IS UNIQUE

I'd like to ensure that the constraint exists without throwing errors.

Is there a way to do this in Cypher? I'm struggling to find any help in the Neo4J documentation.

like image 759
Chris Beach Avatar asked Feb 04 '23 10:02

Chris Beach


1 Answers

Unfortunately there isn't good support for this in Cypher, and even the APOC offering here isn't going to be a good fit due to the side-effect of dropping the non-asserted indexes and constraints.

You'll have to make due with string parsing the results of call db.constraints() and call db.indexes().

UPDATE

In the latest versions of Neo4j (unsure at what point this was changed) it shouldn't throw any errors if attempting to apply a constraint that already exists.

Also, newer versions of APOC have a new dropExisting parameter which allows you to control whether existing schema is dropped or retained prior to applying the new indexes/constraints.

like image 102
InverseFalcon Avatar answered Feb 08 '23 14:02

InverseFalcon