Creating a Node Key Constraint

Set of properties must exist and must be unique

In our Movie data model, we want to ensure every Person in the graph has both name and url properties defined and also that the two properties combined are unique across all nodes.

Recall from earlier in this course that there are two Person nodes with the same name:

cypher
MATCH (p:Person)
WHERE p.name = 'Austin Green'
RETURN p

In the sandbox on the right, modify the code to a Node key constraint for the name and url properties in the graph.

  • constraint_name: Person_name_url_nodekey

  • node_label: Person

  • property_keys: name, url

After you have created the Node key constraint, list all constraints:

cypher
SHOW CONSTRAINTS

Creating Multiple Constraints

If you create incorrect constraints with different names or property_key names, do not worry. You can create new ones, provided the constraint_name or property_key is unique. Later in this course you will learn how to remove constraints from the graph.

If you reload this page, the graph will be reset to what it should be at the beginning of the challenge.

After having created this Node key constraint, this code should return an error:

cypher
MATCH (p:Person)
WHERE p.name = 'Austin Green'
SET p.name = null

This code will also return an error. It finds the Person node by name and then updates it where the constraint is violated:

cypher
MERGE (p:Person {name: 'Austin Green'})
SET p.url = 'https://themoviedb.org/person/1634650'
RETURN p

Validate Results

Once you have created the Node key constraint, click the Check Constraints button and we will check the database for you.

Hint

Constraint names, label names, and property key names are all case-sensitive. The node label you should specify is for Person nodes (case-sensitive). The property keys you should specify are for name and url (case-sensitive).

If you mis-specify a label or property key, the constraint will not be created.

You can type SHOW CONSTRAINTS after you have created each constraint.

If you mess up, you can reload this Challenge page and you should be where you need to be at the beginning of this Challenge.

Solution

Here is the code to create the Node key constraint:

cypher
CREATE CONSTRAINT Person_name_url_nodekey IF NOT EXISTS FOR (x:Person) REQUIRE (x.name,x.url) IS NODE KEY

Summary

In this challenge, you demonstrated that you can create a Node key constraint for multiple node properties in the graph. In the next challenge, you will drop constraints from the graph.