Graph Building - Neo4J
A brief explanation about the creation of the Node with Properties and their Relationship using Cypher Query.
Today, we dive deep into the fascinating world of graph databases, focusing specifically on Neo4j. In this session, we'll explore how to create nodes, define node properties, and establish relationships between them using Neo4j. We'll also cover how to connect Python with Neo4j Desktop to run your queries efficiently.
Before we begin, let's quickly recap some key topics from our previous articles:
🔸 Tab2Graph-1 Conversion of Tabular to Graph using Python, Read here
🔸 For details on the graph data and Graph Neural Network, Read here.
🔸 For details on Graph ML Practical Applications, Read here.
This article will guide you step-by-step through the process of graph data conversion and manipulation, ensuring you have a solid understanding of how to work with Neo4j.
Core Contents of the Article
Let's discuss the tech content of this article; we will be discussing in detail about:
How to Create a Node with Properties in Neo4J
How to Create a Relationship with the Nodes in Neo4 j
How to connect Python with Neo4j Desktop to run Queries.
How to Create a Node with Properties in Neo4J
Lets Open Neo4j Desktop,
To create a node, below is the syntax
CREATE (nodeVariable:Label {property1: value1, property2: value2,…})
Let’s create a Person ‘p’ as a Node,
CREATE (person1: Person {name: 'Alice', age: 25, city: 'London'})
In this example:
person1 is a variable that represents the node.
Person is the label of the node.
Name, age and city are properties of the node.
'Alice', 25 and 'London' are the values assigned to the name, age and city properties.
To view created Nodes,
MATCH (n) RETURN n LIMI 2
This query can be broken down into three parts:
MATCH (n): This part of the query is a
MATCH
clause. It is used to specify a pattern to match the graph. In this case,(n)
is a pattern that matches any node in the graph and assigns it the variablen
.RETURN n: This part of the query is a
RETURN
clause. It specifies what information should be returned as a result of the query. Here, it returns the variable n, which represents the nodes that were matched in theMATCH
clause.LIMIT 2: This part of the query limits the number of results returned. In this case, it limits the result set to 2 nodes.
When you run this query, it will retrieve up to 2 nodes from your graph database. The nodes returned will be any nodes in the graph, as no specific criteria or filters were specified in the MATCH
clause. If there are more than two nodes in your graph, it will return the first two nodes it encounters. Below is the result of the Nodes in Neo4j Desktop
let’s create another node and connect with the persons
CREATE (product1:Product{name: 'Car', price:'€4M',brand:'Ferrari'})
CREATE (product2: Product{name: 'Briyani',Items:'Vegitables,rice, spices,chicken',Time:'2hrs',Style:'Indian'})
In this example, we have created two other nodes named product1 and product2.
Created a node with the label
Product
and assigned it the variableproduct1
. This node has three properties:name
with the value'Car'
,price
with the value'€4M'
, andbrand
with the value'Ferrari'
.Created another node with the label
Product
and assigned it the variableproduct2
. This node has four properties:name
with the value'Briyani'
,Items
with the value'Vegetables,rice,spices,chicken'
,Time
with the value'2hrs'
, andStyle
with the value'Indian'
.
How to Create a Relationship with the Nodes in Neo4J
To create the relationship, the syntax is provided below,
CREATE (node variable)-[:relationship]->(node variable)
Now let’s connect the 'Persons with the Product nodes.
CREATE (person1)-[:cooked]->(product2)
This query creates a node labelled person1
and a node labelled product2
and establishes a directed relationship labelled cooked
from person1
to product2
CREATE
: This keyword is used to create nodes or relationships in the graph.(person1)
: This is a node creation pattern. It creates a node labelledperson1
.-[:cooked]->
: This is a relationship creation pattern. It creates a directed relationship labelledcooked
from oneperson
node to another node.(product2)
: This is another node creation pattern. It creates a node labelledproduct2
.
Likewise, we will create the relationship for other nodes.
CREATE(person2)-[:Purchased]->(product1)
This query creates a node labelled person2
and a node labelled product1
, and establishes the directed relationship labelled Purchased
from person2
to product1
.
CREATE
: As before, this keyword is used to create nodes or relationships.(person2)
: This creates a node labelledperson2
.-[:Purchased]->
: This creates a directed relationship labelledPurchased
from oneperson2
node to another node.(product1)
: This creates a node labelledproduct1
.
CREATE (person1)-[:Cousin_Brother]->(person2)
This query creates a node labelled person1
and a node labelled person2
, and establishes a directed relationship labelled Cousin_Brother
from person1
to person2
.
CREATE
: As before, this keyword is used to create nodes or relationships.(person1)
: This creates a node labelledperson1
.-[:Cousin_Brother]->
: This creates a directed relationship labelledCousin_Brother
from oneperson1
node to another node.(person2)
: This creates a node labelledperson2
.
CREATE(person2)-[:Cousin_Sister]->(person1)
this query creates a node labelled person2
and a node labelled person1
, and establishes a directed relationship labelled Cousin_Sister
from person2
to person1
.
CREATE
: As before, this keyword is used to create nodes or relationships.(person2)
: This creates a node labelledperson2
.-[:Cousin_Sister]->
: This creates a directed relationship labelledCousin_Sister
from oneperson2
node to another node.(person1)
: This creates a node labelledperson1
.
CREATE(person2)-[:Favourite_Food]->(product2) CREATE(Product1)-[:Surprise{Surprise:"Bob want to surprise Alice on her Birthday"}]->(person1)
This query creates two nodes (Product1
and person1
) and establishes a directed relationship labelled Surprise
from Product1
to person1
. This relationship has a property named Surprise, with the value indicating Bob's intention to surprise Alice on her birthday.
CREATE
: This is the keyword used to create nodes or relationships in the graph.(Product1)
: This creates a node with the labelProduct1
.-[:Surprise{Surprise:"Bob want to suprise Alice on her Birthday"}]->
: This part creates a directed relationship labelledSurprise
from theProduct1
node to another node. The relationship has a property namedSurprise
with the value"Bob wants to surprise Alice on her Birthday"
.(person1)
: This creates a node labelledperson1
.
Note :
If we run this above query one by one, since we have a CREATE cypher query, it will create multiple duplicate nodes.
To avoid it there are two possible ways,
🔸 Option-1 :
The simple way to avoid this is by writing all the queries at a time and executing them rather than one by one.
CREATE (person1: Person {name: 'Alice', age: 25, city: 'London'})
CREATE (person2: Person {name: 'bob', age: 30, city: 'Italy'})
CREATE (product1:Product{name: 'Car', price:'€4M',brand:'Ferrari'})
CREATE (product2: Product{name: 'Briyani',Items:'Vegitables,rice, spices,chicken',Time:'2hrs',Style:'Indian'})
CREATE (person1)-[:cooked]->(product2)
CREATE(person2)-[:Purchased]->(product1)
CREATE (person1)-[:Cousin_Brother]->(person2)
CREATE(person2)-[:Cousin_Sister]->(person1)
CREATE(person2)-[:Favourite_Food]->(product2)
CREATE(Product1)-[:Surprise{Surprise:"Bob want to suprise Alice on her Birthday"}]->(person1)
🔸 Option-2 :
Use the MERGE
clause instead of CREATE
to ensure uniqueness based on certain properties.
Using MERGE
will check if a node with specified properties already exists and either match it or create a new one if it doesn't.
MERGE
: This keyword is used to either match an existing pattern in the graph or create a new one if it doesn't exist.ON CREATE
: This is a conditional clause that specifies what actions to take if theMERGE
operation results in the creation of a new node or relationship.SET
: This is a keyword that allows you to set properties on a node or relationship.
MERGE (person1:Person {name: 'Alice'})
ON CREATE SET person1.age = 25, person1.city = 'London'
MERGE (person2:Person {name: 'Bob'})
ON CREATE SET person2.age = 30, person2.city = 'Italy'
MERGE (product1:Product {name: 'Car'})
ON CREATE SET product1.price = '€4M', product1.brand = 'Ferrari'
MERGE (product2:Product {name: 'Briyani'})
ON CREATE SET product2.Items = 'Vegetables,rice,spices,chicken', product2.Time = '2hrs', product2.Style = 'Indian'
MERGE (person2)-[:Purchased]->(product1)
MERGE (person1)-[:Cousin_Brother]->(person2)
MERGE (person2)-[:Cousin_Sister]->(person1)
MERGE (person2)-[:Favourite_Food]->(product2)
MERGE (person1)-[:cooked]->(product2)
MERGE (Product1:Product {name: 'Car'})
MERGE (person1)-[:Surprise {Surprise: "Bob wants to surprise Alice on her Birthday"}]->(Product1)
How to connect Python with Neo4j Desktop to run Queries
Let us check how we can connect a Python Driver to run the queries using Python.
Install the Neo4j Python driver with pip
:
pip install neo4j
from neo4j import GraphDatabase
# URI examples: "neo4j://localhost", "neo4j+s://xxx.databases.neo4j.io"
URI = "<URI for Neo4j database>"
AUTH = ("<Username>", "<Password>")
with GraphDatabase.driver(URI, auth=AUTH) as driver:
driver.verify_connectivity()
# Get the names of all 42-year-olds
records, summary, keys = driver.execute_query(
"MATCH (p:Person {age: $age}) RETURN p.name AS name",
age=42, database_="neo4j",)
# Loop through results and do something with them
for a person in records:
print(person)
# Summary information
print("The query `{query}` returned {records_count} records in {time} ms.".format(
query=summary.query, records_count=len(records),
time=summary.result_available_after,))
This Python code establishes a connection to a Neo4j database, executes a Cypher query to retrieve information about 42-year-old persons, and then prints the results along with some summary information about the query execution.
Thank you very much, and stay tuned for the next Article on Topological Link Prediction using Graph Data Science Library- Neo4J