LightRAG/lightrag/kg/neo4j_impl.py

297 lines
10 KiB
Python
Raw Normal View History

2024-10-26 19:29:45 -04:00
import asyncio
import os
from dataclasses import dataclass
2024-11-06 11:18:14 -05:00
from typing import Any, Union, Tuple, List, Dict
2024-10-29 15:36:07 -04:00
import inspect
2024-11-06 11:18:14 -05:00
from lightrag.utils import logger
from ..base import BaseGraphStorage
from neo4j import (
AsyncGraphDatabase,
exceptions as neo4jExceptions,
AsyncDriver,
AsyncManagedTransaction,
)
2024-10-29 15:36:07 -04:00
2024-10-26 19:29:45 -04:00
from tenacity import (
retry,
stop_after_attempt,
wait_exponential,
retry_if_exception_type,
)
2024-10-26 19:29:45 -04:00
@dataclass
2024-11-02 18:35:07 -04:00
class Neo4JStorage(BaseGraphStorage):
2024-10-26 19:29:45 -04:00
@staticmethod
2024-10-29 15:36:07 -04:00
def load_nx_graph(file_name):
2024-11-06 11:18:14 -05:00
print("no preloading of graph with neo4j in production")
2024-10-26 19:29:45 -04:00
2024-11-02 18:35:07 -04:00
def __init__(self, namespace, global_config):
super().__init__(namespace=namespace, global_config=global_config)
self._driver = None
self._driver_lock = asyncio.Lock()
URI = os.environ["NEO4J_URI"]
USERNAME = os.environ["NEO4J_USERNAME"]
PASSWORD = os.environ["NEO4J_PASSWORD"]
2024-11-06 11:18:14 -05:00
self._driver: AsyncDriver = AsyncGraphDatabase.driver(
URI, auth=(USERNAME, PASSWORD)
)
2024-11-02 18:35:07 -04:00
return None
2024-10-26 19:29:45 -04:00
def __post_init__(self):
self._node_embed_algorithms = {
"node2vec": self._node2vec_embed,
}
2024-11-02 18:35:07 -04:00
async def close(self):
if self._driver:
await self._driver.close()
self._driver = None
async def __aexit__(self, exc_type, exc, tb):
if self._driver:
await self._driver.close()
2024-10-26 19:29:45 -04:00
async def index_done_callback(self):
2024-11-06 11:18:14 -05:00
print("KG successfully indexed.")
2024-11-02 18:35:07 -04:00
2024-10-26 19:29:45 -04:00
async def has_node(self, node_id: str) -> bool:
2024-11-06 11:18:14 -05:00
entity_name_label = node_id.strip('"')
2024-10-26 19:29:45 -04:00
2024-11-06 11:18:14 -05:00
async with self._driver.session() as session:
query = (
f"MATCH (n:`{entity_name_label}`) RETURN count(n) > 0 AS node_exists"
)
result = await session.run(query)
2024-11-02 18:35:07 -04:00
single_result = await result.single()
logger.debug(
2024-11-06 11:18:14 -05:00
f'{inspect.currentframe().f_code.co_name}:query:{query}:result:{single_result["node_exists"]}'
)
2024-10-29 15:36:07 -04:00
return single_result["node_exists"]
2024-11-06 11:18:14 -05:00
2024-10-29 15:36:07 -04:00
async def has_edge(self, source_node_id: str, target_node_id: str) -> bool:
2024-11-06 11:18:14 -05:00
entity_name_label_source = source_node_id.strip('"')
entity_name_label_target = target_node_id.strip('"')
async with self._driver.session() as session:
query = (
f"MATCH (a:`{entity_name_label_source}`)-[r]-(b:`{entity_name_label_target}`) "
"RETURN COUNT(r) > 0 AS edgeExists"
)
result = await session.run(query)
2024-11-02 18:35:07 -04:00
single_result = await result.single()
logger.debug(
2024-11-06 11:18:14 -05:00
f'{inspect.currentframe().f_code.co_name}:query:{query}:result:{single_result["edgeExists"]}'
)
2024-10-29 15:36:07 -04:00
return single_result["edgeExists"]
2024-10-26 19:29:45 -04:00
2024-11-06 11:18:14 -05:00
def close(self):
self._driver.close()
2024-10-26 19:29:45 -04:00
async def get_node(self, node_id: str) -> Union[dict, None]:
2024-11-02 18:35:07 -04:00
async with self._driver.session() as session:
2024-11-06 11:18:14 -05:00
entity_name_label = node_id.strip('"')
2024-11-02 18:35:07 -04:00
query = f"MATCH (n:`{entity_name_label}`) RETURN n"
result = await session.run(query)
record = await result.single()
if record:
node = record["n"]
node_dict = dict(node)
logger.debug(
2024-11-06 11:18:14 -05:00
f"{inspect.currentframe().f_code.co_name}: query: {query}, result: {node_dict}"
2024-11-02 18:35:07 -04:00
)
return node_dict
return None
2024-10-26 19:29:45 -04:00
async def node_degree(self, node_id: str) -> int:
2024-11-06 11:18:14 -05:00
entity_name_label = node_id.strip('"')
2024-10-29 15:36:07 -04:00
2024-11-06 11:18:14 -05:00
async with self._driver.session() as session:
2024-11-02 18:35:07 -04:00
query = f"""
MATCH (n:`{entity_name_label}`)
RETURN COUNT{{ (n)--() }} AS totalEdgeCount
"""
2024-11-06 11:18:14 -05:00
result = await session.run(query)
record = await result.single()
2024-11-02 18:35:07 -04:00
if record:
2024-11-06 11:18:14 -05:00
edge_count = record["totalEdgeCount"]
2024-11-02 18:35:07 -04:00
logger.debug(
2024-11-06 11:18:14 -05:00
f"{inspect.currentframe().f_code.co_name}:query:{query}:result:{edge_count}"
)
2024-11-02 18:35:07 -04:00
return edge_count
2024-11-06 11:18:14 -05:00
else:
2024-11-02 18:35:07 -04:00
return None
2024-10-26 19:29:45 -04:00
async def edge_degree(self, src_id: str, tgt_id: str) -> int:
2024-11-06 11:18:14 -05:00
entity_name_label_source = src_id.strip('"')
entity_name_label_target = tgt_id.strip('"')
2024-11-02 18:35:07 -04:00
src_degree = await self.node_degree(entity_name_label_source)
trg_degree = await self.node_degree(entity_name_label_target)
2024-11-06 11:18:14 -05:00
2024-11-02 18:35:07 -04:00
# Convert None to 0 for addition
src_degree = 0 if src_degree is None else src_degree
trg_degree = 0 if trg_degree is None else trg_degree
degrees = int(src_degree) + int(trg_degree)
logger.debug(
2024-11-06 11:18:14 -05:00
f"{inspect.currentframe().f_code.co_name}:query:src_Degree+trg_degree:result:{degrees}"
)
2024-11-02 18:35:07 -04:00
return degrees
2024-11-06 11:18:14 -05:00
async def get_edge(
self, source_node_id: str, target_node_id: str
) -> Union[dict, None]:
entity_name_label_source = source_node_id.strip('"')
entity_name_label_target = target_node_id.strip('"')
2024-10-26 19:29:45 -04:00
"""
Find all edges between nodes of two given labels
Args:
source_node_label (str): Label of the source nodes
target_node_label (str): Label of the target nodes
Returns:
list: List of all relationships/edges found
"""
2024-11-06 11:18:14 -05:00
async with self._driver.session() as session:
2024-10-26 19:29:45 -04:00
query = f"""
MATCH (start:`{entity_name_label_source}`)-[r]->(end:`{entity_name_label_target}`)
RETURN properties(r) as edge_properties
LIMIT 1
2024-11-06 11:18:14 -05:00
""".format(
entity_name_label_source=entity_name_label_source,
entity_name_label_target=entity_name_label_target,
)
result = await session.run(query)
2024-11-02 18:35:07 -04:00
record = await result.single()
if record:
result = dict(record["edge_properties"])
logger.debug(
2024-11-06 11:18:14 -05:00
f"{inspect.currentframe().f_code.co_name}:query:{query}:result:{result}"
)
return result
else:
return None
2024-10-29 15:36:07 -04:00
2024-11-06 11:18:14 -05:00
async def get_node_edges(self, source_node_id: str) -> List[Tuple[str, str]]:
node_label = source_node_id.strip('"')
2024-10-29 15:36:07 -04:00
"""
2024-11-02 18:35:07 -04:00
Retrieves all edges (relationships) for a particular node identified by its label.
2024-10-29 15:36:07 -04:00
:return: List of dictionaries containing edge information
"""
2024-11-02 18:35:07 -04:00
query = f"""MATCH (n:`{node_label}`)
2024-10-29 15:36:07 -04:00
OPTIONAL MATCH (n)-[r]-(connected)
RETURN n, r, connected"""
2024-11-06 11:18:14 -05:00
async with self._driver.session() as session:
2024-11-02 18:35:07 -04:00
results = await session.run(query)
2024-10-29 15:36:07 -04:00
edges = []
2024-11-02 18:35:07 -04:00
async for record in results:
2024-11-06 11:18:14 -05:00
source_node = record["n"]
connected_node = record["connected"]
source_label = (
list(source_node.labels)[0] if source_node.labels else None
)
target_label = (
list(connected_node.labels)[0]
if connected_node and connected_node.labels
else None
)
2024-10-29 15:36:07 -04:00
if source_label and target_label:
edges.append((source_label, target_label))
2024-10-29 15:36:07 -04:00
2024-11-06 11:18:14 -05:00
return edges
2024-10-29 15:36:07 -04:00
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=4, max=10),
2024-11-06 11:18:14 -05:00
retry=retry_if_exception_type(
(
neo4jExceptions.ServiceUnavailable,
neo4jExceptions.TransientError,
neo4jExceptions.WriteServiceUnavailable,
)
),
)
2024-11-02 18:35:07 -04:00
async def upsert_node(self, node_id: str, node_data: Dict[str, Any]):
2024-10-26 19:29:45 -04:00
"""
2024-11-02 18:35:07 -04:00
Upsert a node in the Neo4j database.
2024-10-26 19:29:45 -04:00
Args:
2024-11-02 18:35:07 -04:00
node_id: The unique identifier for the node (used as label)
node_data: Dictionary of node properties
2024-10-26 19:29:45 -04:00
"""
2024-11-06 11:18:14 -05:00
label = node_id.strip('"')
2024-11-02 18:35:07 -04:00
properties = node_data
2024-10-29 15:36:07 -04:00
2024-11-02 18:35:07 -04:00
async def _do_upsert(tx: AsyncManagedTransaction):
2024-10-26 19:29:45 -04:00
query = f"""
2024-10-29 15:36:07 -04:00
MERGE (n:`{label}`)
SET n += $properties
2024-10-26 19:29:45 -04:00
"""
2024-11-02 18:35:07 -04:00
await tx.run(query, properties=properties)
2024-11-06 11:18:14 -05:00
logger.debug(
f"Upserted node with label '{label}' and properties: {properties}"
)
2024-11-02 18:35:07 -04:00
try:
async with self._driver.session() as session:
await session.execute_write(_do_upsert)
except Exception as e:
logger.error(f"Error during upsert: {str(e)}")
raise
2024-11-06 11:18:14 -05:00
2024-11-02 18:35:07 -04:00
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=4, max=10),
2024-11-06 11:18:14 -05:00
retry=retry_if_exception_type(
(
neo4jExceptions.ServiceUnavailable,
neo4jExceptions.TransientError,
neo4jExceptions.WriteServiceUnavailable,
)
),
2024-11-02 18:35:07 -04:00
)
2024-11-06 11:18:14 -05:00
async def upsert_edge(
self, source_node_id: str, target_node_id: str, edge_data: Dict[str, Any]
):
2024-10-26 19:29:45 -04:00
"""
Upsert an edge and its properties between two nodes identified by their labels.
2024-11-02 18:35:07 -04:00
2024-10-26 19:29:45 -04:00
Args:
2024-11-02 18:35:07 -04:00
source_node_id (str): Label of the source node (used as identifier)
target_node_id (str): Label of the target node (used as identifier)
edge_data (dict): Dictionary of properties to set on the edge
2024-10-26 19:29:45 -04:00
"""
2024-11-06 11:18:14 -05:00
source_node_label = source_node_id.strip('"')
target_node_label = target_node_id.strip('"')
2024-11-02 18:35:07 -04:00
edge_properties = edge_data
2024-10-29 15:36:07 -04:00
2024-11-02 18:35:07 -04:00
async def _do_upsert_edge(tx: AsyncManagedTransaction):
2024-10-29 15:36:07 -04:00
query = f"""
MATCH (source:`{source_node_label}`)
WITH source
MATCH (target:`{target_node_label}`)
2024-10-26 19:29:45 -04:00
MERGE (source)-[r:DIRECTED]->(target)
2024-10-29 15:36:07 -04:00
SET r += $properties
RETURN r
"""
2024-11-02 18:35:07 -04:00
await tx.run(query, properties=edge_properties)
2024-11-06 11:18:14 -05:00
logger.debug(
f"Upserted edge from '{source_node_label}' to '{target_node_label}' with properties: {edge_properties}"
)
2024-11-02 18:35:07 -04:00
try:
async with self._driver.session() as session:
await session.execute_write(_do_upsert_edge)
except Exception as e:
logger.error(f"Error during edge upsert: {str(e)}")
raise
2024-11-06 11:18:14 -05:00
2024-10-26 19:29:45 -04:00
async def _node2vec_embed(self):
2024-11-06 11:18:14 -05:00
print("Implemented but never called.")