Neo4j graph visualiser and serching getting data from aura db
Drop files here
or click to upload
import streamlit as st
import pandas as pd
from neo4j import GraphDatabase
import networkx as nx
from pyvis.network import Network
import json
import tempfile
# Neo4j connection settings
st.sidebar.header("Neo4j Connection Settings")
uri = st.sidebar.text_input("URI", "neo4j+s://xxxxx.databases.neo4j.io")
username = st.sidebar.text_input("Username")
password = st.sidebar.text_input("Password", type="password")
def execute_cypher(query, params=None):
try:
driver = GraphDatabase.driver(uri, auth=(username, password))
with driver.session() as session:
result = session.run(query, params)
records = [record for record in result]
driver.close()
return records
except Exception as e:
st.error(f"Error connecting to Neo4j: {str(e)}")
return None
def visualize_graph(records):
# Create a NetworkX graph
G = nx.Graph()
# Add nodes and edges from the Neo4j records
for record in records:
for item in record.values():
if hasattr(item, 'start_node'): # If it's a relationship
start_node = item.start_node
end_node = item.end_node
relationship_type = item.type
# Add nodes
G.add_node(start_node.id, label=list(start_node.labels)[0],
**dict(start_node.items()))
G.add_node(end_node.id, label=list(end_node.labels)[0],
**dict(end_node.items()))
# Add edge
G.add_edge(start_node.id, end_node.id,
relationship=relationship_type)
elif hasattr(item, 'labels'): # If it's a node
G.add_node(item.id, label=list(item.labels)[0],
**dict(item.items()))
# Create Pyvis network
net = Network(notebook=True, height="600px", width="100%",
bgcolor="#ffffff", font_color="black")
# Add nodes
for node_id in G.nodes():
node_attrs = G.nodes[node_id]
label = node_attrs.get('label', '')
title = '<br>'.join([f"{k}: {v}" for k, v in node_attrs.items()
if k != 'label'])
net.add_node(node_id, label=label, title=title)
# Add edges
for edge in G.edges(data=True):
net.add_edge(edge[0], edge[1], title=edge[2].get('relationship', ''))
# Save and display
with tempfile.NamedTemporaryFile(delete=False, suffix='.html') as tmp:
net.save_graph(tmp.name)
with open(tmp.name, 'r', encoding='utf-8') as f:
html = f.read()
return html
def main():
st.title("Neo4j Graph Explorer")
# Cypher query input
st.header("Cypher Query")
default_query = "MATCH (n)-[r]->(m) RETURN n, r, m LIMIT 100"
cypher_query = st.text_area("Enter Cypher Query", value=default_query, height=100)
# Execute button
if st.button("Execute Query"):
if not all([uri, username, password]):
st.error("Please provide all connection details")
return
records = execute_cypher(cypher_query)
if records:
st.success("Query executed successfully!")
# Display results in table format
st.header("Results Table")
results_list = []
for record in records:
row = {}
for key, value in record.items():
if hasattr(value, 'labels'): # Node
row[key] = f"Node: {dict(value.items())}"
elif hasattr(value, 'type'): # Relationship
row[key] = f"Rel: {value.type}"
else:
row[key] = str(value)
results_list.append(row)
if results_list:
df = pd.DataFrame(results_list)
st.dataframe(df)
# Visualize the graph
st.header("Graph Visualization")
html = visualize_graph(records)
st.components.v1.html(html, height=600)
else:
st.error("No results returned")
if __name__ == "__main__":
main()
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?