Neo4j is a graph relational database. This covers some basic operations you can do with Neo4j
First, install the neo4j
package
pip install neo4j
Define your url, username and password
url, username, password = "bolt://localhost:7687", "neo4j", "096aefa1f03c4b91814138f28c49a1ef"
from neo4j import GraphDatabase
Let’s start with a simple function to list databases
def list_databases(url, user, password):
# Create a driver to connect to the Neo4j instance
driver = GraphDatabase.driver(url, auth=(user, password))
db_names = []
# Connect to the system database, where database management queries are run
with driver.session(database="system") as session:
# Cypher query to list all databases
list_db_query = "SHOW DATABASES"
try:
# Execute the query to list all databases
result = session.run(list_db_query)
# Print the list of databases
print("Available databases:")
for record in result:
print(f"- {record['name']}")
db_names.append(record['name'])
except Exception as e:
print(f"Failed to list databases: {e}")
finally:
driver.close()
return db_names
To create a database we would do
def create_database(uri, user, password, database_name):
# Create a driver to connect to the Neo4j instance
driver = GraphDatabase.driver(uri, auth=(user, password))
# Connect to the system database, as database creation requires admin access
with driver.session(database="system") as session:
# Cypher query to create a new database
create_db_query = f"CREATE DATABASE {database_name}"
try:
# Execute the query to create the database
session.run(create_db_query)
print(f"Database '{database_name}' created successfully.")
except Exception as e:
print(f"Failed to create database: {e}")
finally:
driver.close()