troig troig - 1 year ago 126
Java Question

spring-data-neo4j remove nodeEntity and all referenced nodes

I've got a simple graph model: 1

has N

I'm wondering if there is any way through
to automatically delete all
referenced when I remove an

This is what I've got so far:


public class User implements IdentifiableEntity<String> {

private Long nodeId;
// ...

@RelatedTo(type = "HAS", direction = Direction.OUTGOING)
Set<SocialUser> socialUsers = new HashSet<>();

public class SocialUser implements BasicNodeEntity {

private Long nodeId;

@RelatedTo(type = "HAS", direction = Direction.INCOMING)
User user;


After insert

What I've tried:

In both cases, only
is deleted:

enter image description here

At the moment I've encapsulated the deletion of both entities in a
method in the
service. Something like this:

Neo4jOperations template;

public void delete(String userId) throws Exception {
User user = get(userId);
if (user == null) throw new ResourceNotFoundException("user not found");
Set<SocialUser> socialUsers = template.fetch(user.getSocialUsers());
for (SocialUser socialUser : socialUsers) template.delete(socialUser);

But I'm thinking it's probably not the best way to achieve it. Also I've thought that it could be better to directly execute a
statement to delete all referenced nodes..

Anyone can advise me how to deal with this? Any help would be greatly appreciated. Thanks!

Answer Source

I know it's been a while, but after being a time working with SDN and neo4j, it seems to be that the best way to accomplish this is using a Cypher query.

MATCH (user:User{id:'userId'})-[has:HAS]->(socialUser:SocialUser)
DELETE user, has, socialUser

With SDN, we can take advantadge of repositores:

public interface UserRepository extends Neo4jRepository<User> {

    @Query("MATCH (user:User{id:{id}})-[has:HAS]->(socialUser:SocialUser) DELETE user, has, socialUser")
    void delete(String id);

Hope it helps other people

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download