neo4jcypherneo4j-bolt

Neo4j drop constraint if it does exist


Is there any way of dropping a constraint only if it exists through a query? I am using the bolt driver for javascript.

I initially thought I'll just catch the error, but the error I get is not clear enough:

{"code":"Neo.DatabaseError.Schema.ConstraintDropFailed"}
{ Error: An unexpected failure occurred, see details in the database logs, reference number .... }

In the logs I indeed get:

Unable to drop CONSTRAINT ... No such constraint CONSTRAINT

But I don't want to open the log programmatically and parse it.

Is there any way of dropping the constraint only if it exists? I haven't found anything useful.

The only thing that I can think of is trying first to create two nodes that would conflict with the constraint (which returns a more clear error), but I'd prefer something cleaner.


Solution

  • You can add IF EXISTS to the end of the statement:

    DROP CONSTRAINT SOME_CONSTRAIN IF EXISTS
    

    official documentation: https://neo4j.com/docs/cypher-manual/5/constraints/examples/#administration-constraints-drop-a-non-existing-constraint