3.6. Labels, 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 also 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 will give an example of how to use labels and add constraints and indexes to them. 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 a constraint, and still want an index on the same property, we have to create such an index.

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

Using indexes

For a graph query to run fast, you don’t need indexes, you only need them to find your starting points. The main reason for using indexes in a graph database is to find the starting points in the graph as fast as possible. After the initial index seek you rely on in-graph structures and the first class citizenship of relationships in the graph database to achieve high performance.

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. 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;

Labels

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;