Examples

Examples of how to manage constraints used for ensuring data integrity.

Node property uniqueness constraints

A node property uniqueness constraint ensures that all nodes with a particular label have a set of defined properties whose combined value is unique when existing.

Create a node property uniqueness constraint

When creating a property uniqueness constraint, a name can be provided.

Example 1. CREATE CONSTRAINT
Query
CREATE CONSTRAINT book_isbn
FOR (book:Book) REQUIRE book.isbn IS UNIQUE
Result
Added 1 constraint.

The detailed statistics view currently says Unique constraints added: 1. It will be updated to say Node property uniqueness constraints added: 1 in Neo4j version 6.0.

Handling existing constraints when creating a constraint

Creating an already existing constraint will fail. To avoid such an error, IF NOT EXISTS can be added to the CREATE command. This will ensure that no error is thrown and no constraint is created if any other constraint with the given name or another node property uniqueness constraint on the same schema already exists.

Example 2. CREATE CONSTRAINT
Query
CREATE CONSTRAINT book_isbn2 IF NOT EXISTS
FOR (book:Book) REQUIRE book.isbn2 IS UNIQUE

Assuming no constraint with the given name or other node property uniqueness constraint on the same schema already exists, the query will return:

Result
Added 1 constraint.

The detailed statistics view currently says Unique constraints added: 1. It will be updated to say Node property uniqueness constraints added: 1 in Neo4j version 6.0.

Specifying an index provider when creating a constraint

To create a property uniqueness constraint with a specific index provider for the backing index, the OPTIONS clause is used.

The index type of the backing index is set with the indexProvider option.

The only valid value for the index provider is:

  • range-1.0 Default

Example 3. CREATE CONSTRAINT
Query
CREATE CONSTRAINT constraint_with_options
FOR (book:Book) REQUIRE (book.prop1, book.prop2) IS UNIQUE
OPTIONS {
  indexProvider: 'range-1.0'
}
Result
Added 1 constraint.

The detailed statistics view currently says Unique constraints added: 1. It will be updated to say Node property uniqueness constraints added: 1 in Neo4j version 6.0.

There is no valid index configuration values for the constraint-backing range indexes.

Creating an already existing constraint will fail

Example 4. CREATE CONSTRAINT

Create a property uniqueness constraint on the property published on nodes with the Book label, when that constraint already exists.

Query
CREATE CONSTRAINT book_published FOR (book:Book) REQUIRE book.published IS UNIQUE

In this case the constraint can not be created because it already exists.

Error message
Constraint already exists:
Constraint( id=4, name='preExisting_book_published', type='UNIQUENESS', schema=(:Book {published}), ownedIndex=3 )

The constraint type will be updated to say NODE PROPERTY UNIQUENESS in Neo4j version 6.0.

Creating a constraint on the same schema as an existing index will fail

Example 5. CREATE CONSTRAINT

Create a property uniqueness constraint on the property wordCount on nodes with the Book label, when an index already exists on that label and property combination.

Query
CREATE CONSTRAINT book_word_count FOR (book:Book) REQUIRE book.wordCount IS UNIQUE

In this case the constraint can not be created because there already exists an index covering that schema.

Error message
There already exists an index (:Book {wordCount}).
A constraint cannot be created until the index has been dropped.

Creating a node that complies with an existing constraint

Example 6. CREATE NODE

Create a Book node with an isbn that is not already in the database.

Query
CREATE (book:Book {isbn: '1449356265', title: 'Graph Databases'})
Result
Added 1 label, created 1 node, set 2 properties

Creating a node that violates an existing constraint will fail

Example 7. CREATE NODE

Create a Book node with an isbn that is already used in the database.

Query
CREATE (book:Book {isbn: '1449356265', title: 'Graph Databases'})

In this case the node is not created in the graph.

Error message
Node(0) already exists with label `Book` and property `isbn` = '1449356265'

Creating a constraint when there exist conflicting nodes will fail

Example 8. CREATE CONSTRAINT

Create a property uniqueness constraint on the property title on nodes with the Book label when there are two nodes with the same title.

Query
CREATE CONSTRAINT book_title FOR (book:Book) REQUIRE book.title IS UNIQUE

In this case the constraint can not be created because it is violated by existing data. Either use Indexes for search performance instead, or remove the offending nodes and then re-apply the constraint.

Error message
Unable to create Constraint( name='book_title', type='UNIQUENESS', schema=(:Book {title}) ):
Both Node(0) and Node(1) have the label `Book` and property `title` = 'Moby Dick'

The constraint type will be updated to say NODE PROPERTY UNIQUENESS in Neo4j version 6.0.

The constraint creation fails on the first offending nodes that are found. This does not guarantee that there are no other offending nodes in the data. Therefore, all the data should be checked and cleaned up before re-attempting the constraint creation.

This is an example MATCH query to find all offending nodes with the non-unique property values for the constraint above:

Query
MATCH (book1:Book), (book2:Book)
WHERE book1.title = book2.title AND NOT book1 = book2
RETURN book1, book2

Relationship property uniqueness constraints

This feature was introduced in Neo4j 5.7.

A relationship property uniqueness constraint ensures that all relationships with a particular relationship type have a set of defined properties whose combined value is unique when existing.

Create a relationship property uniqueness constraint

When creating a property uniqueness constraint, a name can be provided.

Example 9. CREATE CONSTRAINT
Query
CREATE CONSTRAINT sequels
FOR ()-[sequel:SEQUEL_OF]-() REQUIRE (sequel.order, sequel.seriesTitle) IS UNIQUE
Result
Added 1 constraint.

The detailed statistics view currently says Relationship uniqueness constraints added: 1. It will be updated to say Relationship property uniqueness constraints added: 1 in Neo4j version 6.0.

Handling existing constraints when creating a constraint

Creating an already existing constraint will fail. To avoid such an error, IF NOT EXISTS can be added to the CREATE command. This will ensure that no error is thrown and no constraint is created if any other constraint with the given name or another relationship property uniqueness constraint on the same schema already exists.

Example 10. CREATE CONSTRAINT
Query
CREATE CONSTRAINT sequels IF NOT EXISTS
FOR ()-[sequel:SEQUEL_OF]-() REQUIRE (sequel.order) IS UNIQUE

Assuming a constraint with the given name already exists:

Result
(no changes, no records)

The detailed statistics view currently says Relationship uniqueness constraints added: 1. It will be updated to say Relationship property uniqueness constraints added: 1 in Neo4j version 6.0.

Specifying an index provider when creating a constraint

To create a property uniqueness constraint with a specific index provider for the backing index, the OPTIONS clause is used.

The index type of the backing index is set with the indexProvider option.

The only valid value for the index provider is:

  • range-1.0 Default

Example 11. CREATE CONSTRAINT
Query
CREATE CONSTRAINT rel_constraint_with_options
FOR ()-[sequel:SEQUEL_OF]-() REQUIRE (sequel.order, sequel.seriesTitle, sequel.number) IS UNIQUE
OPTIONS {
  indexProvider: 'range-1.0'
}
Result
Added 1 constraint.

The detailed statistics view currently says Relationship uniqueness constraints added: 1. It will be updated to say Relationship property uniqueness constraints added: 1 in Neo4j version 6.0.

There are no valid index configuration values for the constraint-backing range indexes.

Creating an already existing constraint will fail

Example 12. CREATE CONSTRAINT

Create a property uniqueness constraint on the properties order and seriesTitle on relationships with the SEQUEL_OF relationship type, when that constraint already exists.

Query
CREATE CONSTRAINT sequel_order_seriestitle FOR ()-[sequel:SEQUEL_OF]-() REQUIRE (sequel.order, sequel.seriesTitle) IS UNIQUE

In this case, the constraint cannot be created because it already exists.

Error message
Constraint already exists:
Constraint( id=13, name='sequels', type='RELATIONSHIP UNIQUENESS', schema=()-[:SEQUEL_OF {order, seriesTitle}]-(), ownedIndex=12 )

The constraint type will be updated to say RELATIONSHIP PROPERTY UNIQUENESS in Neo4j version 6.0.

Creating a constraint on the same schema as an existing index will fail

Example 13. CREATE CONSTRAINT

Create a property uniqueness constraint on the property order on relationships with the SEQUEL_OF relationship type, when an index already exists on that relationship type and property combination.

Query
CREATE CONSTRAINT sequel_series_title FOR ()-[sequel:SEQUEL_OF]-() REQUIRE (sequel.order) IS UNIQUE

In this case, the constraint cannot be created because there already exists an index covering that schema.

Error message
There already exists an index ()-[:SEQUEL_OF {order}]-().
A constraint cannot be created until the index has been dropped.

Creating a relationship that complies with an existing constraint

Example 14. CREATE RELATIONSHIP

Create a SEQUEL_OF relationship with values for properties order and seriesTitle that are not already in the database.

Query
CREATE (:Book {title: 'Spirit Walker'})-[:SEQUEL_OF {order: 1, seriesTitle: 'Chronicles of Ancient Darkness'}]->(:Book {title: 'Wolf Brother'})
Result
Added 2 labels, created 2 nodes, set 4 properties, created 1 relationship.

Creating a relationship that violates an existing constraint will fail

Example 15. CREATE RELATIONSHIP

Create a SEQUEL_OF relationship with values for properties order and seriesTitle that are already used in the database.

Query
MATCH (wolfBrother:Book {title: 'Wolf Brother'}), (spiritWalker:Book {title: 'Spirit Walker'})
CREATE (spiritWalker)-[:SEQUEL_OF {order: 1, seriesTitle: 'Chronicles of Ancient Darkness'}]->(wolfBrother)

In this case, the relationship is not created in the graph.

Error message
Relationship(0) already exists with type `SEQUEL_OF` and properties `order` = 1, `seriesTitle` = 'Chronicles of Ancient Darkness'

Creating a constraint when there exist conflicting relationships will fail

Example 16. CREATE CONSTRAINT

Create a property uniqueness constraint on the property seriesTitle on relationships with the SEQUEL_OF relationship type, when two relationships with the same seriesTitle already exist.

Query
CREATE CONSTRAINT series_title FOR ()-[sequel:SEQUEL_OF]-() REQUIRE (sequel.seriesTitle) IS UNIQUE

In this case, the constraint cannot be created because it is violated by existing data. Either use Indexes for search performance instead, or remove the offending relationships and then re-apply the constraint.

Error message
Unable to create Constraint( name='series_title', type='RELATIONSHIP UNIQUENESS', schema=()-[:SEQUEL_OF {seriesTitle}]-() ):
Both Relationship(0) and Relationship(1) have the type `SEQUEL_OF` and property `seriesTitle` = 'Chronicles of Ancient Darkness'

The constraint creation fails on the first offending relationships that are found. This does not guarantee that there are no other offending relationships in the data. Therefore, all the data should be checked and cleaned up before re-attempting the constraint creation.

This is an example MATCH query to find all offending relationships for the constraint above:

Query
MATCH ()-[knows1:KNOWS]->(), ()-[knows2:KNOWS]->()
WHERE knows1.level = knows2.level AND NOT knows1 = knows2
RETURN knows1, knows2

Node property existence constraints

A node property existence constraint ensures that all nodes with a certain label have a certain property.

Create a node property existence constraint

When creating a node property existence constraint, a name can be provided.

Example 17. CREATE CONSTRAINT
Query
CREATE CONSTRAINT author_name
FOR (author:Author) REQUIRE author.name IS NOT NULL
Result
Added 1 constraint.

The detailed statistics view for property existence constraints, Property existence constraints added: 1, will be split between nodes and relationships in Neo4j version 6.0. For the node property existence constraints, they will say Node property existence constraints added: 1.

Handling existing constraints when creating a constraint

Creating an already existing constraint will fail. To avoid such an error, IF NOT EXISTS can be added to the CREATE command. This will ensure that no error is thrown and no constraint is created if any other constraint with the given name or another node property existence constraint on the same schema already existed.

Example 18. CREATE CONSTRAINT
Query
CREATE CONSTRAINT author_pseudonym IF NOT EXISTS
FOR (author:Author) REQUIRE author.pseudonym IS NOT NULL

Assuming a constraint with the name author_pseudonym already existed:

Result
(no changes, no records)

Creating an already existing constraint will fail

Example 19. CREATE CONSTRAINT

Create a node property existence constraint on the property name on nodes with the Author label, when that constraint already exists.

Query
CREATE CONSTRAINT author_name
FOR (author:Author) REQUIRE author.name IS NOT NULL

In this case the constraint can not be created because it already exists.

Error message
An equivalent constraint already exists, 'Constraint( id=10, name='author_name', type='NODE PROPERTY EXISTENCE', schema=(:Author {name}) )'.

Creating a node that complies with an existing constraint

Example 20. CREATE NODE

Create an Author node with a name property.

Query
CREATE (author:Author {name:'Virginia Woolf'})
Result
Added 1 label, created 1 node, set 1 properties

Creating a node that violates an existing constraint will fail

Example 21. CREATE NODE

Trying to create an Author node without a name property, given a property existence constraint on :Author(name).

Query
CREATE (author:Author)

In this case the node is not created in the graph.

Error message
Node(0) with label `Author` must have the property `name`

Removing an existence constrained node property will fail

Example 22. REMOVE PROPERTY

Trying to remove the name property from an existing node Author, given a property existence constraint on :Author(name).

Query
MATCH (author:Author {name: 'Virginia Woolf'})
REMOVE author.name

In this case the property is not removed.

Error message
Node(0) with label `Author` must have the property `name`

Creating a constraint when there exist conflicting nodes will fail

Example 23. CREATE CONSTRAINT

Create a constraint on the property nationality on nodes with the Author label when there already exists a node without a nationality property.

Query
CREATE CONSTRAINT author_nationality FOR (author:Author) REQUIRE author.nationality IS NOT NULL

In this case the constraint can’t be created because it is violated by existing data. Remove the offending nodes and then re-apply the constraint.

Error message
Unable to create Constraint( type='NODE PROPERTY EXISTENCE', schema=(:Author {nationality}) ):
Node(0) with label `Author` must have the property `nationality`

The constraint creation fails on the first offending node that is found. This does not guarantee that there are no other offending nodes in the data. Therefore, all the data should be checked and cleaned up before re-attempting the constraint creation.

This is an example MATCH query to find all offending nodes missing the property for the constraint above:

Query
MATCH (author:Author)
WHERE author.nationality IS NULL
RETURN author

Relationship property existence constraints

A relationship property existence constraint ensures that all relationships with a certain type have a certain property.

Create a relationship property existence constraint

When creating a relationship property existence constraint, a name can be provided.

Example 24. CREATE CONSTRAINT
Query
CREATE CONSTRAINT wrote_year
FOR ()-[wrote:WROTE]-() REQUIRE wrote.year IS NOT NULL
Result
Added 1 constraint.

The detailed statistics view for property existence constraints, Property existence constraints added: 1, will be split between nodes and relationships in Neo4j version 6.0. For the relationship property existence constraints, they will say Relationship property existence constraints added: 1.

Handling existing constraints when creating a constraint

Creating an already existing constraint will fail. To avoid such an error, IF NOT EXISTS can be added to the CREATE command. This will ensure that no error is thrown and no constraint is created if any other constraint with the given name or another relationship property existence constraint on the same schema already existed.

Example 25. CREATE CONSTRAINT
Query
CREATE CONSTRAINT wrote_year IF NOT EXISTS
FOR ()-[wrote:WROTE]-() REQUIRE wrote.year IS NOT NULL

Assuming that such a constraint already existed:

Result
(no changes, no records)

Creating an already existing constraint will fail

Example 26. CREATE CONSTRAINT

Create a named relationship property existence constraint on the property locations on relationships with the WROTE type, when a constraint with the given name already exists.

Query
CREATE CONSTRAINT wrote_locations
FOR ()-[wrote:WROTE]-() REQUIRE wrote.locations IS NOT NULL

In this case the constraint can not be created because there already exists a constraint with the given name.

Error message
There already exists a constraint called 'wrote_locations'.

Creating a relationship that complies with an existing constraint

Example 27. CREATE RELATIONSHIP

Create a WROTE relationship with a year and location property, given property existence constraints on :WROTE(year) and :WROTE(location).

Query
CREATE (author:Author {name: 'Emily Brontë'})-[wrote:WROTE {year: 1847, location: 'Haworth, United Kingdom'}]->(book:Book {title:'Wuthering Heights', isbn: 9789186579296})
Result
Added 2 labels, created 2 nodes, set 5 properties, created 1 relationship

Creating a relationship that violates an existing constraint will fail

Example 28. CREATE RELATIONSHIP

Trying to create a WROTE relationship without a location property, given a property existence constraint :WROTE(location).

Query
CREATE (author:Author {name: 'Charlotte Brontë'})-[wrote:WROTE {year: 1847}]->(book:Book {title: 'Jane Eyre', isbn:9780194241762})

In this case the relationship is not created in the graph.

Error message
Relationship(0) with type `WROTE` must have the property `location`

Removing an existence constrained relationship property will fail

Example 29. REMOVE PROPERTY

Trying to remove the location property from an existing relationship of type WROTE, given a property existence constraint :WROTE(location).

Query
MATCH (author:Author)-[wrote:WROTE]->(book:Book) REMOVE wrote.location

In this case the property is not removed.

Error message
Relationship(0) with type `WROTE` must have the property `location`

Creating a constraint when there exist conflicting relationships will fail

Example 30. CREATE CONSTRAINT

Create a constraint on the property language on relationships with the WROTE type when there already exists a relationship without a property named language.

Query
CREATE CONSTRAINT wrote_language FOR ()-[wrote:WROTE]-() REQUIRE wrote.language IS NOT NULL

In this case the constraint can not be created because it is violated by existing data. Remove the offending relationships and then re-apply the constraint.

Error message
Unable to create Constraint( type='RELATIONSHIP PROPERTY EXISTENCE', schema=()-[:WROTE {language}]-() ):
Relationship(0) with type `WROTE` must have the property `language`

The constraint creation fails on the first offending relationship that are found. This does not guarantee that there are no other offending relationships in the data. Therefore, all the data should be checked and cleaned up before re-attempting the constraint creation.

This is an example MATCH query to find all offending relationships missing the property for the constraint above:

Query
MATCH ()-[wrote:WROTE]-()
WHERE wrote.language IS NULL
RETURN wrote

Node key constraints

A node key constraint ensures that all nodes with a particular label have a set of defined properties whose combined value is unique and all properties in the set are present.

Create a node key constraint

When creating a node key constraint, a name can be provided.

Example 31. CREATE CONSTRAINT
Query
CREATE CONSTRAINT actor_fullname
FOR (actor:Actor) REQUIRE (actor.firstname, actor.surname) IS NODE KEY
Result
Added 1 constraint.

Handling existing constraints when creating a constraint

Creating an already existing constraint will fail. To avoid such an error, IF NOT EXISTS can be added to the CREATE command. This will ensure that no error is thrown and no constraint is created if any other constraint with the given name or another node key constraint on the same schema already exists.

Example 32. CREATE CONSTRAINT
Query
CREATE CONSTRAINT actor_names IF NOT EXISTS
FOR (actor:Actor) REQUIRE (actor.firstname, actor.surname) IS NODE KEY

Assuming a node key constraint on (:Actor {firstname, surname}) already existed:

Result
(no changes, no records)

Specifying an index provider when creating a constraint

To create a node key constraint with a specific index provider for the backing index, the OPTIONS clause is used.

The index type of the backing index is set with the indexProvider option.

The only valid value for the index provider is:

  • range-1.0 Default

Example 33. CREATE CONSTRAINT
Query
CREATE CONSTRAINT constraint_with_provider
FOR (actor:Actor) REQUIRE (actor.surname) IS NODE KEY
OPTIONS {
  indexProvider: 'range-1.0'
}
Result
Added 1 constraint.

There is no valid index configuration values for the constraint-backing range indexes.

Node key and property uniqueness constraints are not allowed on the same schema

Example 34. CREATE CONSTRAINT

Create a node key constraint on the properties firstname and age on nodes with the Actor label, when a property uniqueness constraint already exists on the same label and property combination.

Query
CREATE CONSTRAINT actor_name_age FOR (actor:Actor) REQUIRE (actor.firstname, actor.age) IS NODE KEY

In this case the constraint can not be created because there already exist a conflicting constraint on that label and property combination.

Error message
Constraint already exists:
Constraint( id=10, name='preExisting_actor_name_age', type='UNIQUENESS', schema=(:Actor {firstname, age}), ownedIndex=9 )

Creating a constraint on same name as an existing index will fail

Example 35. CREATE CONSTRAINT

Create a named node key constraint on the property citizenship on nodes with the Actor label, when an index already exists with the given name.

Query
CREATE CONSTRAINT citizenship
FOR (actor:Actor) REQUIRE actor.citizenship IS NODE KEY

In this case the constraint can’t be created because there already exists an index with the given name.

Error message
There already exists an index called 'citizenship'.

Creating a node that complies with an existing constraint

Example 36. CREATE NODE

Create an Actor node with firstname and surname properties.

Query
CREATE (actor:Actor {firstname: 'Keanu', surname: 'Reeves'})
Result
Added 1 label, created 1 node, set 2 properties.

Creating a node that violates an existing constraint will fail

Example 37. CREATE NODE

Trying to create an Actor node without a firstname property, given a node key constraint on :Actor(firstname, surname), will fail.

Query
CREATE (actor:Actor {surname: 'Wood'})

In this case the node is not created in the graph.

Error message
Node(0) with label `Actor` must have the properties (`firstname`, `surname`)

Removing a NODE KEY-constrained property will fail

Example 38. REMOVE PROPERTY

Trying to remove the firstname property from an existing node Actor, given a NODE KEY constraint on :Actor(firstname, surname).

Query
MATCH (actor:Actor {firstname: 'Keanu', surname: 'Reeves'}) REMOVE actor.firstname

In this case the property is not removed.

Error message
Node(0) with label `Actor` must have the properties (`firstname`, `surname`)

Creating a constraint when there exist conflicting node will fail

Example 39. CREATE CONSTRAINT

Trying to create a node key constraint on the property born on nodes with the Actor label will fail when a node without a born property already exists in the database.

Query
CREATE CONSTRAINT actor_born FOR (actor:Actor) REQUIRE (actor.born) IS NODE KEY

In this case the node key constraint can not be created because it is violated by existing data. Either use Indexes for search performance instead, or remove the offending nodes and then re-apply the constraint.

Error message
Unable to create Constraint( type='NODE KEY', schema=(:Actor {born}) ):
Node(0) with label `Actor` must have the property `born`

The constraint creation fails on the first offending nodes that are found. This does not guarantee that there are no other offending nodes in the data. Therefore, all the data should be checked and cleaned up before re-attempting the constraint creation.

This is an example MATCH query to find all offending nodes for the constraint above:

Query
MATCH (actor1:Actor), (actor2:Actor)
WHERE actor1.born = actor2.born AND NOT actor1 = actor2
UNWIND [actor1, actor2] AS actor
RETURN actor, 'non-unique' AS reason

UNION

MATCH (actor:Actor)
WHERE actor.born IS NULL
RETURN actor, 'non-existing' AS reason

Relationship key constraints

This feature was introduced in Neo4j 5.7.

A relationship key constraint ensures that all relationships with a particular relationship type have a set of defined properties whose combined value is unique. It also ensures that all properties in the set are present.

Create a relationship key constraint

When creating a relationship key constraint, a name can be provided.

Example 40. CREATE CONSTRAINT
Query
CREATE CONSTRAINT knows_since_how
FOR ()-[knows:KNOWS]-() REQUIRE (knows.since, knows.how) IS RELATIONSHIP KEY
Result
Added 1 constraint.

Handling existing constraints when creating a constraint

Creating an already existing constraint will fail. To avoid such an error, IF NOT EXISTS can be added to the CREATE command. This will ensure that no error is thrown and no constraint is created if any other constraint with the given name or another relationship key constraint on the same schema already exists.

Example 41. CREATE CONSTRAINT
Query
CREATE CONSTRAINT knows IF NOT EXISTS
FOR ()-[knows:KNOWS]-() REQUIRE (knows.since, knows.how) IS RELATIONSHIP KEY

Assuming a relationship key constraint on ()-[:KNOWS {since, how}]-() already existed:

Result
(no changes, no records)

Specifying an index provider when creating a constraint

To create a relationship key constraint with a specific index provider for the backing index, the OPTIONS clause is used.

The index type of the backing index is set with the indexProvider option.

The only valid value for the index provider is:

  • range-1.0 Default

Example 42. CREATE CONSTRAINT
Query
CREATE CONSTRAINT rel_constraint_with_provider
FOR ()-[knows:KNOWS]-() REQUIRE (knows.since) IS REL KEY
OPTIONS {
  indexProvider: 'range-1.0'
}
Result
Added 1 constraint.

There is no valid index configuration values for the constraint-backing range indexes.

Relationship key and property uniqueness constraints are not allowed on the same schema

Example 43. CREATE CONSTRAINT

Create a relationship key constraint on the property how on relationships with the KNOWS relationship type, when a property uniqueness constraint already exists on the same relationship type and property combination.

Query
CREATE CONSTRAINT knows_how FOR ()-[knows:KNOWS]-() REQUIRE (knows.how) IS REL KEY

In this case, the constraint cannot be created because there already exists a conflicting constraint on that relationship type and property combination.

Error message
Constraint already exists:
Constraint( id=34, name='preExisting_how', type='RELATIONSHIP UNIQUENESS', schema=()-[:KNOWS {how}]-(), ownedIndex=33 )

The constraint type for relationship property uniqueness constraints will be updated to say RELATIONSHIP PROPERTY UNIQUENESS in Neo4j version 6.0.

Creating a constraint on same name as an existing index will fail

Example 44. CREATE CONSTRAINT

Create a named relationship key constraint on the property level on relationships with the KNOWS relationship type, when an index already exists with the given name.

Query
CREATE CONSTRAINT knows
FOR ()-[knows:KNOWS]-() REQUIRE (knows.level) IS REL KEY

In this case, the constraint cannot be created because there already exists an index with the given name.

Error message
There already exists an index called 'knows'.

Creating a relationship that complies with an existing constraint

Example 45. CREATE RELATIONSHIP

Create a KNOWS relationship with both since and how properties and a relationship key constraint on :KNOWS(since, how).

Query
CREATE (:Actor {firstname: 'Jensen', surname: 'Ackles'})-[:KNOWS {since: 2008, how: 'coworkers'}]->(:Actor {firstname: 'Misha', surname: 'Collins'})
Result
Added 2 labels, created 2 nodes, set 6 properties, created 1 relationship.

Creating a relationship that violates an existing constraint will fail

Example 46. CREATE RELATIONSHIP

Trying to create a KNOWS relationship without a since property, given a relationship key constraint on :KNOWS(since, how), will fail.

Query
MATCH (jensen:Actor {firstname: 'Jensen', surname: 'Ackles'}), (misha:Actor {firstname: 'Misha', surname: 'Collins'})
CREATE (misha)-[:KNOWS {how: 'coworkers'}]->(jensen)

In this case, the relationship is not created in the graph.

Error message
Relationship(0) already exists with type `KNOWS` and property `how` = 'coworkers'

Removing a RELATIONSHIP KEY-constrained property will fail

Example 47. REMOVE PROPERTY

Trying to remove the since property from an existing relationship KNOWS, given a RELATIONSHIP KEY constraint on :KNOWS(since, how).

Query
MATCH ()-[knows:KNOWS {since: 2008, how: 'coworkers'}]->() REMOVE knows.since

In this case, the property is not removed.

Error message
Relationship(0) with type `KNOWS` must have the properties (`since`, `how`)

Creating a constraint when there exist conflicting relationships will fail

Example 48. CREATE CONSTRAINT

Trying to create a relationship key constraint on the property level on relationships with the KNOWS relationship type will fail when two relationships with identical level property values already exist in the database.

Query
CREATE CONSTRAINT knows_level FOR ()-[knows:KNOWS]-() REQUIRE (knows.level) IS REL KEY

In this case, the relationship key constraint cannot be created because it is violated by existing data. Either use Indexes for search performance instead, or remove the offending relationships and then re-apply the constraint.

Error message
Unable to create Constraint( name='knows_level', type='RELATIONSHIP KEY', schema=()-[:KNOWS {level}]-() ):
Both Relationship(0) and Relationship(1) have the type `KNOWS` and property `level` = 10

The constraint creation fails on the first offending relationships that are found. This does not guarantee that there are no other offending relationships in the data. Therefore, all the data should be checked and cleaned up before re-attempting the constraint creation.

This is an example MATCH query to find all offending relationships for the constraint above:

Query
MATCH ()-[knows1:KNOWS]->(), ()-[knows2:KNOWS]->()
WHERE knows1.level = knows2.level AND NOT knows1 = knows2
UNWIND [knows1, knows2] AS knows
RETURN knows, 'non-unique' AS reason
UNION
MATCH ()-[knows:KNOWS]->()
WHERE knows.level IS NULL
RETURN knows, 'non-existing' AS reason

Drop a constraint by name

Drop a constraint

A constraint can be dropped using the name with the DROP CONSTRAINT constraint_name command. It is the same command for uniqueness, property existence, and node/relationship key constraints. The name of the constraint can be found using the SHOW CONSTRAINTS command, given in the output column name.

Example 49. DROP CONSTRAINT
Query
DROP CONSTRAINT book_isbn
Result
Removed 1 constraint.

Drop a non-existing constraint

If it is uncertain if any constraint with a given name exists and you want to drop it if it does but not get an error should it not, use IF EXISTS. It is the same command for uniqueness, property existence, and node/relationship key constraints.

Example 50. DROP CONSTRAINT
Query
DROP CONSTRAINT missing_constraint_name IF EXISTS
Result
(no changes, no records)

Listing constraints

Listing all constraints

To list all constraints with the default output columns, the SHOW CONSTRAINTS command can be used. If all columns are required, use SHOW CONSTRAINTS YIELD *.

One of the output columns from SHOW CONSTRAINTS is the name of the constraint. This can be used to drop the constraint with the DROP CONSTRAINT command.

Example 51. SHOW CONSTRAINTS
Query
SHOW CONSTRAINTS
╒════╤══════════════════════════════╤═════════════════════════════════╤══════════════╤═══════════════╤════════════════════════════════╤══════════════════════════════╕
│"id"│"name"                        │"type"                           │"entityType"  │"labelsOrTypes"│"properties"                    │"ownedIndex"                  │
╞════╪══════════════════════════════╪═════════════════════════════════╪══════════════╪═══════════════╪════════════════════════════════╪══════════════════════════════╡
│23  │"actor_fullname"              │"NODE_KEY"                       │"NODE"        │["Actor"]      │["firstname","surname"]         │"actor_fullname"              │
├────┼──────────────────────────────┼─────────────────────────────────┼──────────────┼───────────────┼────────────────────────────────┼──────────────────────────────┤
│16  │"author_name"                 │"NODE_PROPERTY_EXISTENCE"        │"NODE"        │["Author"]     │["name"]                        │null                          │
├────┼──────────────────────────────┼─────────────────────────────────┼──────────────┼───────────────┼────────────────────────────────┼──────────────────────────────┤
│19  │"author_pseudonym"            │"UNIQUENESS"                     │"NODE"        │["Author"]     │["pseudonym"]                   │"author_pseudonym"            │
├────┼──────────────────────────────┼─────────────────────────────────┼──────────────┼───────────────┼────────────────────────────────┼──────────────────────────────┤
│6   │"book_isbn2"                  │"UNIQUENESS"                     │"NODE"        │["Book"]       │["isbn2"]                       │"book_isbn2"                  │
├────┼──────────────────────────────┼─────────────────────────────────┼──────────────┼───────────────┼────────────────────────────────┼──────────────────────────────┤
│8   │"constraint_with_options"     │"UNIQUENESS"                     │"NODE"        │["Book"]       │["prop1","prop2"]               │"constraint_with_options"     │
├────┼──────────────────────────────┼─────────────────────────────────┼──────────────┼───────────────┼────────────────────────────────┼──────────────────────────────┤
│25  │"constraint_with_provider"    │"NODE_KEY"                       │"NODE"        │["Actor"]      │["surname"]                     │"constraint_with_provider"    │
├────┼──────────────────────────────┼─────────────────────────────────┼──────────────┼───────────────┼────────────────────────────────┼──────────────────────────────┤
│30  │"knows_since_how"             │"RELATIONSHIP_KEY"               │"RELATIONSHIP"│["KNOWS"]      │["since","how"]                 │"knows_since_how"             │
├────┼──────────────────────────────┼─────────────────────────────────┼──────────────┼───────────────┼────────────────────────────────┼──────────────────────────────┤
│27  │"preExisting_actor_name_age"  │"UNIQUENESS"                     │"NODE"        │["Actor"]      │["firstname","age"]             │"preExisting_actor_name_age"  │
├────┼──────────────────────────────┼─────────────────────────────────┼──────────────┼───────────────┼────────────────────────────────┼──────────────────────────────┤
│10  │"preExisting_book_published"  │"UNIQUENESS"                     │"NODE"        │["Book"]       │["published"]                   │"preExisting_book_published"  │
├────┼──────────────────────────────┼─────────────────────────────────┼──────────────┼───────────────┼────────────────────────────────┼──────────────────────────────┤
│34  │"preExisting_how"             │"RELATIONSHIP_UNIQUENESS"        │"RELATIONSHIP"│["KNOWS"]      │["how"]                         │"preExisting_how"             │
├────┼──────────────────────────────┼─────────────────────────────────┼──────────────┼───────────────┼────────────────────────────────┼──────────────────────────────┤
│15  │"rel_constraint_with_options" │"RELATIONSHIP_UNIQUENESS"        │"RELATIONSHIP"│["SEQUEL_OF"]  │["order","seriesTitle","number"]│"rel_constraint_with_options" │
├────┼──────────────────────────────┼─────────────────────────────────┼──────────────┼───────────────┼────────────────────────────────┼──────────────────────────────┤
│32  │"rel_constraint_with_provider"│"RELATIONSHIP_KEY"               │"RELATIONSHIP"│["KNOWS"]      │["since"]                       │"rel_constraint_with_provider"│
├────┼──────────────────────────────┼─────────────────────────────────┼──────────────┼───────────────┼────────────────────────────────┼──────────────────────────────┤
│13  │"sequels"                     │"RELATIONSHIP_UNIQUENESS"        │"RELATIONSHIP"│["SEQUEL_OF"]  │["order","seriesTitle"]         │"sequels"                     │
├────┼──────────────────────────────┼─────────────────────────────────┼──────────────┼───────────────┼────────────────────────────────┼──────────────────────────────┤
│21  │"wrote_locations"             │"RELATIONSHIP_PROPERTY_EXISTENCE"│"RELATIONSHIP"│["WROTE"]      │["location"]                    │null                          │
├────┼──────────────────────────────┼─────────────────────────────────┼──────────────┼───────────────┼────────────────────────────────┼──────────────────────────────┤
│20  │"wrote_year"                  │"RELATIONSHIP_PROPERTY_EXISTENCE"│"RELATIONSHIP"│["WROTE"]      │["year"]                        │null                          │
└────┴──────────────────────────────┴─────────────────────────────────┴──────────────┴───────────────┴────────────────────────────────┴──────────────────────────────┘
15 rows

The type column returns UNIQUENESS for the node property uniqueness constraint and RELATIONSHIP_UNIQUENESS for the relationship property uniqueness constraint. This will be updated in Neo4j version 6.0. Node property uniqueness constraints will be updated to NODE_PROPERTY_UNIQUENESS and relationship property uniqueness constraints to RELATIONSHIP_PROPERTY_UNIQUENESS.

Listing constraints with filtering

One way of filtering the output from SHOW CONSTRAINTS by constraint type is the use of type keywords, listed in the syntax for listing constraints type filter table. For example, to show only property uniqueness constraints, use SHOW UNIQUENESS CONSTRAINTS. Another more flexible way of filtering the output is to use the WHERE clause. An example is to only show constraints on relationships.

Example 52. SHOW CONSTRAINTS
Query
SHOW EXISTENCE CONSTRAINTS
WHERE entityType = 'RELATIONSHIP'

This will only return the default output columns. To get all columns, use SHOW INDEXES YIELD * WHERE ....

╒════╤═════════════════╤═════════════════════════════════╤══════════════╤═══════════════╤════════════╤════════════╕
│"id"│"name"           │"type"                           │"entityType"  │"labelsOrTypes"│"properties"│"ownedIndex"│
╞════╪═════════════════╪═════════════════════════════════╪══════════════╪═══════════════╪════════════╪════════════╡
│21  │"wrote_locations"│"RELATIONSHIP_PROPERTY_EXISTENCE"│"RELATIONSHIP"│["WROTE"]      │["location"]│null        │
├────┼─────────────────┼─────────────────────────────────┼──────────────┼───────────────┼────────────┼────────────┤
│20  │"wrote_year"     │"RELATIONSHIP_PROPERTY_EXISTENCE"│"RELATIONSHIP"│["WROTE"]      │["year"]    │null        │
└────┴─────────────────┴─────────────────────────────────┴──────────────┴───────────────┴────────────┴────────────┘
2 rows