Creating, Inserting, and Querying Data in Neo4j with Python

02.10.2024

Neo4j is a popular graph database that allows you to model your data as nodes, relationships, and properties. In this article, we will explore how to create, insert, and query data in Neo4j using Python.

Cypher: LOAD JSON from URL AS Data - Graph Database & Analytics

Creating a Connection to Neo4j

Before we can start working with Neo4j in Python, we need to establish a connection to the Neo4j database. We can use the official Neo4j Python driver, neo4j, to interact with the database.

Training Series: Neo4j Aura Free – YouTube
Sep 14, 2021 … Interested in testing a project, building a proof-of-concept, or playing with a graph database – all without handling database …
from neo4j import GraphDatabase  uri = "bolt://localhost:7687" username = "neo4j" password = "password"  driver = GraphDatabase.driver(uri, auth=(username, password)) 

Inserting Data

Once we have established a connection to Neo4j, we can start inserting data into the database. We can use Cypher, Neo4j’s query language, to create nodes and relationships.

Here’s an example of how we can insert a node representing a person:

def create_person(tx, name):     tx.run("CREATE (p:Person {name: $name})", name=name)  with driver.session() as session:     session.write_transaction(create_person, "Alice") 

Querying Data

After inserting data into Neo4j, we can query the database to retrieve information. We can use Cypher to search for specific nodes, relationships, or properties.

Here’s an example of how we can query the database to find all people:

def get_people(tx):     result = tx.run("MATCH (p:Person) RETURN p.name AS name")     return [record["name"] for record in result]  with driver.session() as session:     people = session.read_transaction(get_people)     for person in people:         print(person) 

Conclusion

In this article, we have learned how to create a connection to Neo4j, insert data into the database, and query the data using Python. By combining the power of Neo4j with the flexibility of Python, you can build powerful graph-based applications.

Yan Hadzhyisky

fullstack PHP+JS+REACT developer