Spring Data Neo4J @Index(unique = true) does not working

Viewed 2192

I want to make userName property in User node as a unique. I used below code but it doesn't create a unique constraint in the Neo4j database.

@Property(name = "name")
@Index(unique = true)
private String usreName;

FYI, I'm using the Neo4j Server version: 3.3.6 (community) With Spring Boot 2.
but if I create a constraint in the Neo4j Browser by myself, it works.

CREATE CONSTRAINT ON (user:User) ASSERT user.userName IS UNIQUE

Is there a way to force Spring Data Neo4J to create unique properties, without creating them by myself in Database?

4 Answers

Reason

In Spring Data Neo4j 4, index management concerns were removed from the mapping framework entirely.

(from Index Management in Spring Data Neo4j)

Solution

@Autowired
private SessionFactory sessionFactory;

@PostConstruct
public void createIndexesAndConstraints() {
    Session session = sessionFactory.openSession();
    Result result = session.query("CREATE INDEX ON :User(userName)", Collections.EMPTY_MAP);
}

You can configure the mode our auto index manager works in through application.properties

spring.data.neo4j.auto-index=validate # or
# spring.data.neo4j.auto-index=update
# spring.data.neo4j.auto-index=assert

Default mode is none. Apart from that, what @meistermeier says applies.

Also, Neo4jOperations was deprecated in SDN 4 something and has been removed in SDN 5. Use Session instead for operations "near" the database.

Thank you @ThirstForKnowledg for your answer. But I have 3 other Questions:
1- I'm using Spring Boot 2, and I can not see Neo4jOperations in my classpath to import it.

2- Should I put this in my Entity node or in another bean?
3- What about after running my application two or more times? I think it would cause an exception for the second time or more.

Related