Search code examples
indexingneo4jcypher

Neo4j: how do I use an index in a relationship between two nodes?


I'm debugging the code of an api and I found a cypher instruction that takes 6 minutes to return the data.

I ran the neo4j code in smaller chunks and found that this snippet is causing the problem: MATCH(copart:CopartOperadora) WHERE NOT (copart)-[:FROM_TO]->(:Coexistence)

I'm new to neo4j so I still haven't figured out how I can optimize this instruction.

Thanks to everyone who contributed.


Solution

  • Optimizations of this kind, usually depend on the schema, of your graph database, without that it's very hard to provide any insights. But you can try this:

    MATCH (copart:CopartOperadora)-[:FROM_TO]->(:Coexistence)
    WITH collect(id(copart)) AS connectedNodesIds
    MATCH (copart:CopartOperadora) WHERE id(copart) NOT IN connectedNodesIds
    

    We can't create any index as such, unfortunately. But if the relationship FROM_TO is only present from CopartOperadora to Coexistence nodes. Then you can remove the node label for Coexistence, all together, which will be optimal. Something like this:

    MATCH(copart:CopartOperadora) WHERE NOT (copart)-[:FROM_TO]->()