4.5. Labels, Constraints and Indexes

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

The following will give an example of how to use labels. Let’s start out adding a constraint — in this case we decided that all Movie node titles should be unique.

CREATE CONSTRAINT ON (movie:Movie) ASSERT movie.title IS UNIQUE

Note that adding the unique constraint will add an index on that property, so we won’t do that separately. If we drop the constraint, we will have to add an index instead, as needed.

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

CREATE INDEX ON :Actor(name)

Indexes can be added at any time. Constraints can be added after a label is already in use, but that requires that the existing data complies with the constraints. Note that it will take some time for an index to come online when there’s existing data.

Now, let’s add some data.

CREATE (actor:Actor { name:"Tom Hanks" }),(movie:Movie { title:'Sleepless IN Seattle' }),
  (actor)-[:ACTED_IN]->(movie);

Normally you don’t specify indexes when querying for data. They will be used automatically. This means we 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;

Now let’s say we want to add another label for a node. Here’s how to do that:

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

To remove a label from nodes, this is what to do:

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

For more information on labels and related topics, see: