Warm tip: This article is reproduced from serverfault.com, please click

Neo4j: How to call "CREATE INDEX" only if not exists

发布于 2020-04-01 15:07:27

The CREATE INDEX <indexName> command is not idempotent and will cause an error if the given index already exists. I'm new to neo4j, and can't find a predicate that avoids this error. I've tried various permutations of ANY(...), and they all barf at "db.indexes()".

Since CREATE INDEX ... fails if the index exists and DROP INDEX ... fails if it doesn't, I don't know how to write a .cypher file that creates the index only if needed.

A short form might be something like CREATE INDEX indexName FOR (c:SomeLabel) ON (c.someProperty) IF NOT EXISTS, but of course that short form doesn't exist.

Is there some way to do this with a predicate, subquery or some such expression?

Questioner
Tom Stambaugh
Viewed
0
Tom Stambaugh 2020-04-08 06:56:35

I tried both suggestions, and neither solves my issue. I don't have time to discover, through trial-and-error, how to install APOC in my environment.

The first line of mbh86's answer is inaccurate, at least in my system. The command is not ignored, it fails with an error. So if anything else is in the same cypher script, it will fail.

The best I can do is apparently to wrap the CREATE INDEX in a command-line string, run that string from either a bash or python script, run it, and check the return code from the calling program.

I appreciate the effort of both commentators, and I didn't want to leave either hanging.