Basics of Neo4j

Dhruv Saksena
2 min readFeb 22, 2022

--

Neo4j is a graph database and is different from row, columnar or no-sql database. It has different nodes and they are inter-connected to each other with relationships.

Following are the commands to create nodes in Neo4j-n

Creating a Node

create(n:Employee)

Create a Node with properties

CREATE (n:Employee{code : 'TV74545', designation: 'TL', name: 'TL1'})

Search all Nodes

MATCH(n) RETURN n

Set properties to a Node

MATCH(n)
SET n.name= 'Dhruv' , n.code='TVW6235723'
RETURN n

Search for a specific node

MATCH (node1: Employee) 
where node1.code ='TVW6235723'
RETURN node1

Return multiple nodes

MATCH(node1:Employee), (node2: Employee)
WHERE node1.code = 'TVW6235723' and node2.code = 'TUV762137'
RETURN node1,node2

Create relationship between two nodes

MATCH (a:Employee), (b:Employee) WHERE a.code = "TVW6235723" AND b.code = "TUV762137"CREATE (a)-[r: MANAGES]->(b)RETURN a,b

Search nodes of a specific property

MATCH(emp:Employee {designation: 'Manager'}) 
RETURN emp

Select nodes without any incoming relationship

MATCH (p:Employee)
WHERE NOT (p)<-[:MANAGES]-()
RETURN p

Select nodes with no specific relationships

MATCH (p:Employee)
WHERE NOT (p)-[:MANAGES]-()
RETURN p

Select nodes without any outgoing relationship

MATCH (p:Employee)
WHERE NOT (p)-[:MANAGES]->()
RETURN p

Manage all orphan nodes

A simple use case to map all the orphan nodes to VP-

MATCH (orphanEmployeeNodes:Employee),(vpNode:Employee)
WHERE (NOT (orphanEmployeeNodes)-[:MANAGES]-()) AND vpNode.designation='VP'
CREATE (vpNode)-[r:MANAGES]->(orphanEmployeeNodes)RETURN orphanEmployeeNodes, vpNode

Get parent hierarchy of node till nth level

Here, “7” indicate the level to which you want to find the parent hierarchy

MATCH(node:Employee) ,(parent: Employee)
where node.code= 'TV74545' and (parent)-[:MANAGES*1..7]->(node)RETURN(parent)

--

--