How to check if an index exist in neo4j cypher
Asked Answered
H

3

5

I am trying to find a way to check if a certain index exists in cypher schema indexes. I can find all the indexes by using call db.indexes() . but how can I check for a specific index?

Hottempered answered 2/10, 2018 at 12:29 Comment(0)
M
5

If you want the index to exist, I would recommend just running the Cypher to create the index. The result being that whether the index existed or not, after the call it is guaranteed to exist.

On the other hand, if you just want the information for display purposes or something, you can use YIELD to continue a cypher from a CALL. For example...

CALL db.indexes() YIELD label, properties WHERE label="Person" RETURN *

For db.indexes, the variables you can yield are description, label, properties, provider, state, type (you have to yield them by name, YIELD a,b,c,d,e,f won't work)

Misrepresent answered 2/10, 2018 at 14:32 Comment(4)
even though I did it by parsing result this is pure gold .. thanks @MisrepresentHottempered
My problem is that neo4j throws an error if you try to create an index that already exists. Is there a way to create an index that won't throw an error if the index already exists?Hoff
@Hoff Then either you need to put a lock on the caller so they know they already called create index, or use the APOC extention like cybersam suggests.Misrepresent
After neo4j 4.3 use the new Index creation syntax: Neo4j: How to call "CREATE INDEX" only if not existsTautologize
O
4

The APOC plugin has an apoc.schema.node.indexExists function for determining whether a specific index exists.

Oberland answered 2/10, 2018 at 18:38 Comment(2)
Yes, but how do you use it as a conditional? That will return true or false, but the value of that is meaningless in the real world unless you can make it part of another execution.Impatiens
You can use the APOC procedures apoc.when or apoc.do.when to perform if-then-else processing.Oberland
C
0

In the current Neo4J 5 in 2024, you can use SHOW INDEXES (or SHOW CONSTRAINTS) and it will present a list

Docs: Managing Indexes Manual

OR, you can just create the desired index or constraint with the "IF NOT EXISTS" clause, and it will add it only if it isn't in place yet.

Example:

    CREATE INDEX <index_name> IF NOT EXISTS
    FOR (x:<node_label>)
    ON x.<property_key>

Docs: CREATE INDEX IF NOT EXISTS

Claypool answered 26/4, 2024 at 16:3 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.