Create Node and Relationship in one query : Spring Data Neo4j

577 views Asked by At

I am trying to create new nodes and relationships using Neo4j using Spring Data Neo4j. My use case is to add a friend relationship between 2 user nodes. So this boils down to :

User user1 = userRepo.findByPropertyValue("userId1", userId1);
User user2 = userRepo.findByPropertyValue("userId2", userId2);

if(user1 == null){
    createUserObject(userId1);
}

if(user2 == null){
    createUserObject(userId2);
}

user1.isFriend(user2);

userRepo.save();

So this includes 2 calls to the DB (findByPropertyValue). Is this correct or is there another way to do this ? Maybe batch the whole thing up into one request ?

Thanks..

1

There are 1 answers

0
Michael Hunger On

You can do both with a single cypher query:

START user1=node:User(userId={userId1}),
      user2=node:User(userId={userId2})
CREATE UNIQUE (user1)-[:FRIEND]-(user2);

The user-id's are passed in as params in a map.

You can also use an annotated repository method for that.