Pages

October 01, 2019

#Neo4j Part 2: Interview Questions & Answers (Create Node and Relationships)

How can we create node in Neo4j?
Creating a Single node: We can create a single node by executing below query. Semicolon is optional.

CREATE (node_name); 

Creating Multiple Nodes: We can create multiple nodes at the same time by using below query:

CREATE (node1),(node2),(node3)

Creating a Node with a Label: In Neo4j a label in Neo4j is used to group the nodes. We can create a node with label by using below command:
CREATE (node:label) 

Creating a Node with Multiple Labels: We can also create multiple labels for a single node by using below command:

CREATE (node:label1:label2:...labeln)

Create Node with Properties: Properties are the key-value pairs using which a node stores data. We can create a node with properties using the CREATE clause by specifying the properties separated by commas within the {}.

CREATE (node:label { key1: value, key2: value,..})
e.g CREATE(Employee:Developer{name:"himanshu",surname:"shukla",id:1})

Returning the Created Node: We can use the RETURN clause with CREATE to view the newly created node.

CREATE (Node:Label{properties. . . . }) RETURN Node
e.g CREATE(Employee:Developer{name:"Andrew",surname:"Hudson",id:1}) RETURN Employee;

How can we create relationships in Neo4j?
Creating the Relationships : To create a relationship using the CREATE clause we need to specify relationship within the square braces '[ ]' depending on the direction of the relationship it is placed between hyphen ' - ' and arrow '→' .

CREATE (node1)-[:RelationshipType]->(node2) 
e.g
CREATE(Employee:Developer{name:"himanshu shukla",id:1})
CREATE (Ind:Country {name: "India"})
CREATE (Employee)-[r:STAYS_IN]->(Ind) 

Creating a Relationship Between the Existing Nodes: We can also create a relationship between the existing nodes using the MATCH clause. e.g:

MATCH (a:LabeofNode1), (b:LabeofNode2) 
WHERE a.name = "nameofnode1" AND b.name = " nameofnode2" 
CREATE (a)-[: Relation]->(b) 
RETURN a,b

Lets say we created two nodes:
CREATE(Employee:Developer{name:"himanshu shukla",id:1})
CREATE (Ind:Country {name: "India"})

Now we want to add a relationship between the two.
MATCH (a:Developer), (b:Country) WHERE a.name = "himanshu shukla" AND b.name = "India" 
CREATE (a)-[r: LIVES_IN]->(b) 
RETURN a,b 

Creating a Relationship with Label and Properties: We can create a relationship with label and properties using the CREATE clause.

CREATE (node1)-[label:Rel_Type {key1:value1, key2:value2, . . . n}]-> (node2)

Lets say we created two nodes:
CREATE(Employee:Developer{name:"himanshu shukla",id:1})
CREATE (Ind:Country {name: "India"})

Now we want to add a relationship between the two.
MATCH (a:Developer), (b:Country) WHERE a.name = "himanshu shukla" AND b.name = "India"
CREATE (a)-[r: LIVES_IN {Staying_Since:1990,Region:"North"}]->(b)
RETURN a,b


-K Himaanshu Shuklaa..

No comments:

Post a Comment