I want to add a Relationship between two already existing nodes in Neo4j - how to do that using Spring Data Neo4jRepository?

66 Views Asked by At

The cypher query to perform the above task would be as follows:

MATCH (a:Buyer), (b:Seller) MERGE (a) -[:BUY {quantity: 150}]-> (b);

I want the equivalent Neo4jRepository function or some equivalent code that can serve the same above purpose. Please post the answer if you know some solution.

[Updates]

I have posted an answer below. But I am also expecting some other kind of solutions to this purpose. Please feel free to post alternative solutions as answers.

1

There are 1 best solutions below

0
Kalpadiptya Roy On

One Possible Way

If we have two Nodes/Entities as Buyer and Stock as POJO classes in SpringBoot Code, and if we are trying to add a relationship called [:HAS] between two such nodes then we can do the following.

@Node("Stock")
class Stock
{
   @Id @GeneratedValue(...)
   private Long id;
   
   /* Other attributes here --- */
}

@Node("Buyer")
class Buyer
{
   @Id @GeneratedValue(...)
   private Long id;
   /* Other Attribute Variables Here --- */

   @Relationship(type="HAS")
   private List<Stock> stockList;

   public List<Stock> getStockList()
   {
       return stockList;
   }

   public void setStockList(List stockList)
   {
       this.stockList = stockList;
   }

}

So we can do this to create the desired relationship.

buyer.getStockList().add(newStock);
buyerRepo.save(buyer);

Here buyerRepo is the object of a Repository that implements Neo4jRepository<Buyer, Long>