from neo4j import GraphDatabase
driver = GraphDatabase.driver(
"bolt://localhost:7687",
auth=("neo4j", "password")
)
def create_knowledge_graph(session):
"""Build a knowledge graph from extracted entities."""
session.run("""
CREATE (python:Technology {name: 'Python', type: 'Language'})
CREATE (django:Framework {name: 'Django', type: 'Web Framework'})
CREATE (orm:Component {name: 'Django ORM', type: 'ORM'})
CREATE (pg:Database {name: 'PostgreSQL', type: 'RDBMS'})
CREATE (django)-[:BUILT_WITH]->(python)
CREATE (django)-[:INCLUDES]->(orm)
CREATE (orm)-[:CONNECTS_TO]->(pg)
CREATE (orm)-[:MAPS {description: 'Python objects to database tables'}]->(pg)
""")
def graph_retrieval(session, question: str) -> str:
"""Retrieve relevant subgraph for a question."""
# Extract key entity from question
entity = extract_key_entity(question) # e.g., "Django"
# Traverse graph to find related nodes within 2 hops
result = session.run("""
MATCH (start {name: $entity})-[r*1..2]-(connected)
RETURN start.name AS source,
[rel IN r | type(rel)] AS relationships,
connected.name AS target,
connected.type AS target_type
""", entity=entity)
# Format as context for LLM
context_parts = []
for record in result:
path = f"{record['source']} -> {' -> '.join(record['relationships'])} -> {record['target']} ({record['target_type']})"
context_parts.append(path)
return "\n".join(context_parts)
with driver.session() as session:
context = graph_retrieval(session, "How does Django connect to databases?")
print(context)
# Django -> INCLUDES -> Django ORM (ORM)
# Django ORM -> CONNECTS_TO -> PostgreSQL (RDBMS)
# Django -> BUILT_WITH -> Python (Language)