Usman Mutawakil
Usman Mutawakil

Reputation: 5259

Cypher: Creating a schema index that already exists

When you ask Neo4j to create an index that already exists it does not thrown an exception, which seems good for my purpose.

session.run("CREATE INDEX ON :User(email)");

Question 1:

But how is neo4j handling this under the hood? Does it delete the index then recreate it or does it ignore the query altogether since the index already exists?

I'd like to know because I have some CRUD operations and I'd like to define the schema for my nodes at the moment I create them, which means calling "CREATE INDEX" and so fourth. The drawback is this means for every new node created redundant calls to create an index are made, which is fine if they are ignored if the index already exists.

Question 2:

I noticed the following works even if no nodes exist with the label User yet (Meaning I can create labels and index before the associated nodes).

CREATE INDEX ON :User(email)

I'm new to Neo4j and use to the RDBMS world where you can't create an index on a column that does not exist. Am I correct in my belief that creating Indexes and labels before I've even created the nodes that have those labels and properties should not cause any unforeseen problems down the road?

Upvotes: 2

Views: 1638

Answers (2)

Usman Mutawakil
Usman Mutawakil

Reputation: 5259

Question 1

This won't work if you are creating constraints. They can only be called once and if they exist THEY will indeed throw an exception. Normal indexes don't seem to do so this whole approach should not be attempted.

Question 2

See InverseFalcons comment but it seems to be the correct approach.

Upvotes: 0

InverseFalcon
InverseFalcon

Reputation: 30407

Answering question #2, creating indexes and constraints even when no nodes with those labels or properties exist is perfectly fine, and is in fact an extremely common case. I highly recommend going this route.

I'd recommend against creating indexes with every node creation. While I don't believe it causes much in wasted cycles, it doesn't seem like good design.

Upvotes: 2

Related Questions