Reputation: 776
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.
Upvotes: 0
Views: 1740
Reputation: 1347
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
Upvotes: 2
Reputation: 67009
If you know all the indexes and constraints that you want, you can use the apoc procedure apoc.schema.assert to make that they exist and that all other existing indexes and constraints are dropped.
An example of how to use this procedure is part of this doc section. Here is a snippet showing a call to the procedure and the results:
Let’s create some indexes and constraints, note that other indexes and constraints will be dropped by this.
CALL apoc.schema.assert(
{Track:['title','length']},
{Artist:['name'],Track:['id'],Genre:['name']});
╒════════════╤═══════╤══════╤═══════╕
│label │key │unique│action │
╞════════════╪═══════╪══════╪═══════╡
│Track │title │false │CREATED│
├────────────┼───────┼──────┼───────┤
│Track │length │false │CREATED│
├────────────┼───────┼──────┼───────┤
│Artist │name │true │CREATED│
├────────────┼───────┼──────┼───────┤
│Genre │name │true │CREATED│
├────────────┼───────┼──────┼───────┤
│Track │id │true │CREATED│
└────────────┴───────┴──────┴───────┘
Upvotes: 1