Neo4j - Create an Index using Cypher

An index is a data structure that improves the speed of data retrieval operations in a database.

In Neo4j, you can create an index over a property on any node that has been given a label. Once you create an index, Neo4j will manage it and keep it up to date whenever the database is changed.

To create an index, use the CREATE INDEX ON statement. Like this:

In the above example, we create an index on the Name property of all nodes with the Album label.

When the statement succeeds,the following message is displayed:

Screenshot of the success message.

When you create an index, Neo4j will create the index in the background. If your database is large, this may take some time.

Only when Neo4j has finished creating the index, will it be brought online, and it can be used in queries.

View the Index

Indexes (and constraints) become part of the (optional) database schema.

In the Neo4j browser, you can review all indexes and constraints by using the :schema command.

Simply type this:

You will see a list of any indexes and constraints:

Screenshot of the schema listing.

Index Hints

Once an index has been created, it will automatically be used when you perform relevant queries.

However, Neo4j also allows you to enforce one or more indexes with a hint. You can create an index hint by including USING INDEX ... in your query.

So we could enforce the above index as follows:

You can also provide multiple hints. Simply add a new USING INDEX for each index you'd like to enforce.

To Index or Not to Index?

When Neo4j creates an index, it creates a redundant copy of the data in the database. Therefore using an index will result in more disk space being utilized, plus slower writes to the disk.

Therefore, you need to weigh up these factors when deciding which data/properties to index.

Generally, it's a good idea to create an index when you know there's going to be a lot of data on certain nodes. Also, if you find queries are taking too long to return, adding an index may help.