How to check a constraint already exists in Neo4J 4.0

constraint_command = "CREATE CONSTRAINT ID ON (n:" + label + ") ASSERT n.ID IS UNIQUE"

My database may already have such a constraint. Before my program executes this statement, I need a way to tell whether it already had this constraint. It seems in Neo4j 3.5, it didn't complain even if it already exits. But in 4.0, it gives this error message:

neobolt.exceptions.ClientError: An equivalent constraint already exists, 'Constraint( UNIQUE, :Product(ID) )'.

How to check before creating it?


You can get database constraints with this command CALL db.constraints(), you just need after to compare strings :)

1 Like

I must say - this is a frustrating change... makes for a LOT more lines of code.

I'm trying to follow the logic to write a validation check (just to add a constraint) - I need to CALL db.contraints() Find if there is a match, but only continue on if there isn't a match, and rinse-repeat for EVERY constraint I want to create.

Could you provide an example code to do this? Is there a function that makes this easier to accomplish?

I'm still a bit baffled by this change.

Have a look at apoc.schema.assert() to see if that would work for you. Be aware that the default for dropExisting is true and it will drop all existing indexes/constraints that are not included in the command.

1 Like

Hello @pdrangeid :slight_smile:

Yeah I found this very frustrating as well :confused: Which language are you using?


I was still drafting my reply when I saw the reference to assert. Is anyone surprised that it was APOC to the rescue? :grin:

CALL apoc.schema.assert(null,{Assetcategory:['name']},False)

This works VERY well.

Actually works BETTER using APOC, because you can list MULTIPLE labels/properties within ONE apoc CALL, so you can perform your indexes/constraints in FEWER lines of code than native Cypher.