2.2.5. Constraints and indexes

Labels are a convenient way to group nodes together. They are used to restrict queries, define constraints and create indexes. Using constraints

You can specify unique constraints that guarantee uniqueness of a certain property on nodes with a specific label. These constraints are also used by the MERGE clause to make certain that a node only exists once.

The following is an example of how to use labels and add constraints and indexes to them. Let’s start out by adding a constraint. In this case we decide that every Movie node should have a unique title.


Note that adding the unique constraint will implicitly add an index on that property, so we won’t have to do that separately. If we drop a constraint but still want an index on that property, we will have to create the index explicitly.

Constraints can be added after a label is already in use, but that requires that the existing data complies with the constraints. Using indexes

The main reason for using indexes in a graph database is to find the starting point in the graph as fast as possible. After that seek you rely on in-graph structures and the first class citizenship of relationships in the graph database to achieve high performance. Thus graph queries themselves do not need indexes to run fast.

Indexes can be added at any time. Note that it will take some time for an index to come online when there’s existing data.

In this case we want to create an index to speed up finding actors by name in the database:

CREATE INDEX ON :Actor(name)

Now, let’s add some data.

CREATE (actor:Actor { name:"Tom Hanks" }),(movie:Movie { title:'Sleepless IN Seattle' }),

Normally you don’t specify indexes when querying for data. They will be used automatically. This means we that can simply look up the Tom Hanks node, and the index will kick in behind the scenes to boost performance.

MATCH (actor:Actor { name: "Tom Hanks" })
RETURN actor;