Pages

October 01, 2019

#Neo4j Part 5:Interview Questions & Answers (Delete, Remove and ForEach clause)

Explain Delete clause of Neo4j.
In Neo4j we can delete nodes and relationships from a database by using the DELETE clause.

Delete a single node
MATCH (n:Person { name: 'UNKNOWN' })  
DELETE n  


Deleting All Nodes and Relationships: Below query will delete all the nodes and relationships from Neo4j.
MATCH (n) DETACH DELETE n

Deleting a Particular Node With Its Relationship: To delete a particular node, we need to mention the details of the node in the place of 'n' in the above mentioned query.
MATCH (node:label {properties . . . . . . . . . .  }) 
DETACH DELETE node

e.g:
MATCH (Employee:Developer{name:"seba",id:2})
DETACH DELETE Employee

Delete relationships only:
MATCH(x)-[r:RELATES_TO]->(y)
DELETE r

e.g:
MATCH (n { name: 'himanshu' })-[r:KNOWS]->()  

DELETE r  

Explain the remove clause of Neo4j.
We can remove properties and labels from Nodes or Relationships using the Remove clause. The main difference between Neo4j CQL DELETE and REMOVE commands is, the DELETE operation is used to delete nodes and associated relationships, where as REMOVE is used to remove labels and properties.

Removing a Property
MATCH (node:label{properties . . . . . . . }) 
REMOVE node.property 
RETURN node

e.g:
MATCH(Employee:Developer{name:"seba",id:2})
REMOVE Employee.id
RETURN Employee;

Removing a Label From a Node
MATCH (node:label {properties . . . . . . . . . . . }) 
REMOVE node:label 
RETURN node 

e.g:
MATCH(Employee:Developer{name:"seba",id:2})
REMOVE Employee:Lead
RETURN Employee;

Removing Multiple Labels: We can remove multiple labels as well.
MATCH (node:label1:label2 {properties . . . . . . . . }) 
REMOVE node:label1:label2 
RETURN node

e.g:
MATCH(Employee:Developer{name:"seba",id:2})
REMOVE Employee:Lead:Tester
RETURN Employee;

Explain forEach clause.
It is used to update data within a list whether components of a path, or result of aggregation.

MATCH p = (start node)-[*]->(end node) 
WHERE start.node = "node_name" AND end.node = "node_name" 
FOREACH (n IN nodes(p)| SET n.marked = TRUE) 

Lets create a path in Neo4j

CREATE e=(Employee:Employee{name:"himanshu shukla",id:1})-[:WORKS_IN]->(Department:Department{name:"development center"})-[:LOCATED_IN]->(City:City{name:"munich"})
RETURN e

Following is a sample Cypher Query which adds a property to all the nodes along the path using the FOREACH clause.

MATCH x=(Employee)-[*]->(City)
WHERE Employee.name="himanshu shukla" AND City.name="munich"
FOREACH (n IN nodes(x)| SET n.marked = TRUE)
RETURN x;




-K Himaanshu Shuklaa..

No comments:

Post a Comment