How to check if a schema index already exists for a node's property in neo4j?

这一生的挚爱 提交于 2019-12-24 05:42:01

问题


I am using IndexDefinition for populating index over a given property in neo4j.

IndexDefinition indexDefinition = schema.indexFor(DynamicLabel.label("Person")).on("NodeType").create();

Problem is when I execute the program again with similar code for Index population, I get following exception.

 org.neo4j.kernel.api.exceptions.schema.AlreadyIndexedException: Already indexed :label[0](property[0]).
    at org.neo4j.kernel.impl.api.DataIntegrityValidatingStatementContext.checkIndexExistence(DataIntegrityValidatingStatementContext.java:107)
    at org.neo4j.kernel.impl.api.DataIntegrityValidatingStatementContext.indexCreate(DataIntegrityValidatingStatementContext.java:78)

I just want to check if an Index for a property is already there, then no subsequent Index population should take place.


回答1:


why don't you check the Indexes for a Label before trying to create it and getting a (correct) exception?

http://api.neo4j.org/2.0.0-M03/org/neo4j/graphdb/schema/Schema.html#getIndexes(org.neo4j.graphdb.Label)




回答2:


Here's a helper function that I'm using in my code, so I don't forget to wrap it in a tx.

/**
 * Helper method to get indexes by Label, wrapped in a tx
 * 
 * @param label
 * @return one or more IndexDefinitions to iterate over, or null if there
 *         were none matching the label.
 */
public Iterable<IndexDefinition> getIndexByLabel(Label label) {
    Iterable<IndexDefinition> x = null;
    try (Transaction tx = graphDb.beginTx()) {
        x = graphDb.schema().getIndexes(label);
    }
    return x;
}



回答3:


You can know if any node/relationship index is created for a particular label as follows

IndexManager indexManager = graphDb.index();
indexManager.existsForNodes();


来源:https://stackoverflow.com/questions/17718076/how-to-check-if-a-schema-index-already-exists-for-a-nodes-property-in-neo4j

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!