Creating Uniqueness Constraints

Uniqueness required

In our Movie data model, we want to ensure that nodes are unique. In your real application, you would create uniqueness constraints for nodes prior to loading the data. For this course, we already have the data loaded, but we still want to constrain the graph so that nodes are unique.

In the previous lesson, you executed code to create a uniqueness constraint for Movie nodes. In this Challenge, you will create three more uniqueness constraints in the graph.

In the sandbox on the right, modify the code to create these uniqueness constraints in the graph:

  1. For the Person nodes:

    • constraint_name: Person_tmdbId_unique

    • node_label: Person

    • property_key: tmdbId

  2. For the User nodes:

    • constraint_name: User_userId_unique

    • node_label: User

    • property_key: userId

  3. For the Genre nodes:

    • constraint_name: Genre_name_unique

    • node_label: Genre

    • property_key: name

After you have created the constraints, list them:

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.

Validate Results

Once you have created the three constraints, click the Check Database button and we will check the database for you.

Hint

Constraint names, label names, and property key names are all case-sensitive. The node labels you should specify are for Person, User, and Genre nodes (case-sensitive). The property keys you should specify are for tmdbId, userId, and name (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.

Then you would need to recreate the three existence constraints for Person, User, and Genre nodes.

Solution

Here are the statements to create these two constraints:

cypher
CREATE CONSTRAINT Person_tmdbId_unique IF NOT EXISTS FOR (x:Person) REQUIRE x.tmdbId IS UNIQUE;
CREATE CONSTRAINT User_userId_unique IF NOT EXISTS FOR (x:User) REQUIRE x.userId IS UNIQUE;
CREATE CONSTRAINT Genre_name_unique IF NOT EXISTS FOR (x:Genre) REQUIRE x.name IS UNIQUE

Summary

In this challenge, you demonstrated that you can create uniqueness constraints in the graph. In the next lesson, you will learn how to create existence constraints.