13.2. Constraints
Neo4j helps enforce data integrity with the use of constraints.
You can use unique constraints to ensure that property values are unique for all nodes with a specific label. Unique constraints do not mean that all nodes have to have a unique value for the properties — nodes without the property are not subject to this rule.
Remember that adding constraints is an atomic operation that can take a while — all existing data has to be scanned before Neo4j can turn the constraint “on”.
You can have multiple unique constraints for a given label.
Note that adding a uniqueness constraint on a property will also add an index on that property, so you cannot add such an index separately. Cypher will use that index for lookups just like other indexes. If you drop a constraint and still want an index on the property, you will have to create the index.
Create uniqueness constraint
To create a constraint that makes sure that your database will never contain more than one node with a specific label and one property value, use the IS
UNIQUE
syntax.
Query.
CREATE CONSTRAINT ON (book:Book) ASSERT book.isbn IS UNIQUE
Result
Constraints added: 1 |
---|
|
Try this query live. none CREATE CONSTRAINT ON (book:Book) ASSERT book.isbn IS UNIQUE
Drop uniqueness constraint
By using DROP
CONSTRAINT
, you remove a constraint from the database.
Query.
DROP CONSTRAINT ON (book:Book) ASSERT book.isbn IS UNIQUE
Result
Constraints removed: 1 |
---|
|
Create a node that complies with constraints
Create a Book
node with an isbn
that isn’t already in the database.
Query.
CREATE (book:Book { isbn: '1449356265', title: 'Graph Databases' })
Result
Nodes created: 1 |
---|
Properties set: 2 |
Labels added: 1 |
|
Create a node that breaks a constraint
Create a Book
node with an isbn
that is already used in the database.
Query.
CREATE (book:Book { isbn: '1449356265', title: 'Graph Databases' })
Error message.
Node 0 already exists with label Book and property "isbn"=[1449356265]