Monday, 2 August 2021

Neo4j: Add relationship to existing nodes

Step 1: Open neo4j browser by hitting following url in browser.

http://localhost:7474/browser/

 


Step 2: Create nodes by executing below command.

CREATE (r:Person{name: "Rama Krishna", age: 32, city: "Bangalore", male: true}), (m:Person{name: "Murali Krishna", age: 34, city: "Hyderabad", male: true}) RETURN r, m




Step 3: Add LIKES relationship between Rama Krishna and Murali Krishna by executing below query.

MATCH (p1:Person{name: "Rama Krishna"}), (p2:Person{name: "Murali Krishna"}) CREATE (p1)-[:LIKES]->(p2)

 

 


Step 4: Get the nodes to see the relationship.

MATCH (n:Person) RETURN n




We can even add even specify the same relationship between p2 and p1 by executing below command.

 

MATCH (p1:Person{name: "Rama Krishna"}), (p2:Person{name: "Murali Krishna"}) CREATE (p1)<-[:LIKES]-(p2)

 

 


Get the nodes

MATCH (n:Person) RETURN n

 

 


Problem of creating relationship using CREATE clause

CREATE clause create new relationship even though there is already same relationship exist.

 

For example, execute below command.

MATCH (p1:Person{name: "Rama Krishna"}), (p2:Person{name: "Murali Krishna"}) CREATE (p1)-[:LIKES]->(p2) CREATE (p1)<-[:LIKES]-(p2) RETURN p1, p2




Rerun the same command again.




How to solve above problem?

Use MERGE clause to create relationships. MERGE clause creates a relationship if it not exists.

 

Delete all the nodes by executing below command.

 

Create nodes by executing below command.

CREATE (r:Person{name: "Rama Krishna", age: 32, city: "Bangalore", male: true}), (m:Person{name: "Murali Krishna", age: 34, city: "Hyderabad", male: true}) RETURN r, m

 

 


 

Execute below command to create LIKES relation between two nodes.

 

MATCH (p1:Person{name: "Rama Krishna"}), (p2:Person{name: "Murali Krishna"})

MERGE (p1)-[:LIKES]->(p2)

MERGE (p1)<-[:LIKES]-(p2)

RETURN p1, p2




Rerun the same command any number of times, it do not create any new relationship.

Previous                                                    Next                                                    Home

No comments:

Post a Comment