Skip to content

Neo4j - Constrains & Nodes

During this part of the tutorial we will focus on exploring what the constrains and indexes are.

We will start by adding constrains and indexes to a small database that can hold persons and countries.

Constraints & Indexes

Constraints can be used in the free version of Neo4j to add the unique property restrictions for a label. At the same time it also adds an index for that property to make searches with that property faster.

Indexes can be added to properties to make searches with that property faster.

Info

Do note that although index makes it faster to search for data with the given property, it also slows down writes to your database and your database will need to store additional data to keep the indexes data stored.
So really only add index or constrains to properties where you need it, not everywhere!

Learn more about constrains, Learn more about indexes

Adding a Constraint

First, let's start by add a property constraint for the label Person. This will also create the label at the same time:

Cypher
CREATE CONSTRAINT person_id FOR (p: Person) REQUIRE p.userId IS UNIQUE
Example Output
Added 1 constraints

And let's also create another for the label Country:

Cypher
CREATE CONSTRAINT country_id FOR (p: Country) REQUIRE p.countryId IS UNIQUE
Example Output
Added 1 constraints

Listing Schemas

Now, to view what we have created, the command :schema can be used:

Cypher
:schema
Example Output
Index Name      Type    Uniqueness  EntityType  LabelsOrTypes   Properties      State
person_email    BTREE   NONUNIQUE   NODE        [ "Person" ]    [ "email" ]     ONLINE
person_id       BTREE   UNIQUE      NODE        [ "Person" ]    [ "userId" ]    ONLINE

With this command we can see all the constraints and indexes created for the database.

Adding an Index

it is also possible to add indexes for the properties. For this case, let's add an index for the Person label's property email so that we can later find persons with certain email address faster:

Cypher
CREATE INDEX person_email FOR (p: Person) ON (p.email)
Example Output
Added 1 index

Now, after running the :schema command again, we can see all the indexes in our database.

Note

Note that creating the constrains and indexes above is completely optional, but helpful to create some basic structure for the database.

Removing Constraints & Indexes

The syntax for removing a constraint or index can be found from the official Neo4j documentation: