2
votes

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
I have successfully integrated Liquigraph that is a tool that executes a .xml changelog with the Neo4j Cypher commands (the one you are using "CREATE CONSTRAINT ON (user:User) ASSERT user.userName IS UNIQUE"). Have a look at my answer below and vote it! ThanksPaolo De Dominicis

4 Answers

4
votes

You need to configure the auto index manager if you want the application code create the constraints. You can find the best fitting option in the documentation: https://docs.spring.io/spring-data/neo4j/docs/current/reference/html/#reference:indexing:creation

Just a note on this topic: Think about the auto index creation like Hibernate's DDL support. It is a helper at development time. You should not use assert and update in production environments but only validate.

1
votes

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);
}
0
votes

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.

-1
votes

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.