fix: get_knowledge_graph return null when query an isolated node

This commit is contained in:
yangdx
2025-04-16 11:14:48 +08:00
parent ccd67cdff7
commit a3de6b75a8

View File

@@ -1720,8 +1720,8 @@ class PGGraphStorage(BaseGraphStorage):
strip_label = node_label.strip('"') strip_label = node_label.strip('"')
count_query = f"""SELECT * FROM cypher('{self.graph_name}', $$ count_query = f"""SELECT * FROM cypher('{self.graph_name}', $$
MATCH (n:base {{entity_id: "{strip_label}"}}) MATCH (n:base {{entity_id: "{strip_label}"}})
OPTIONAL MATCH p = (n:base)-[*..{max_depth}]->(m:base) OPTIONAL MATCH p = (n)-[*..{max_depth}]-()
RETURN count(distinct m) AS total_nodes RETURN count(nodes(p)) AS total_nodes
$$) AS (total_nodes bigint)""" $$) AS (total_nodes bigint)"""
count_result = await self._query(count_query) count_result = await self._query(count_query)
@@ -1731,19 +1731,25 @@ class PGGraphStorage(BaseGraphStorage):
# Now get the actual data with limit # Now get the actual data with limit
if node_label == "*": if node_label == "*":
query = f"""SELECT * FROM cypher('{self.graph_name}', $$ query = f"""SELECT * FROM cypher('{self.graph_name}', $$
MATCH (n:base) MATCH (node:base)
OPTIONAL MATCH (n:base)-[r]->(target:base) OPTIONAL MATCH (node)-[r]->()
RETURN collect(distinct n) AS n, collect(distinct r) AS r RETURN collect(distinct node) AS n, collect(distinct r) AS r
LIMIT {max_nodes} LIMIT {max_nodes}
$$) AS (n agtype, r agtype)""" $$) AS (n agtype, r agtype)"""
else: else:
strip_label = node_label.strip('"') strip_label = node_label.strip('"')
query = f"""SELECT * FROM cypher('{self.graph_name}', $$ if total_nodes > 0:
MATCH (n:base {{entity_id: "{strip_label}"}}) query = f"""SELECT * FROM cypher('{self.graph_name}', $$
OPTIONAL MATCH p = (n:base)-[*..{max_depth}]->(m:base) MATCH (node:base {{entity_id: "{strip_label}"}})
RETURN nodes(p) AS n, relationships(p) AS r OPTIONAL MATCH p = (node)-[*..{max_depth}]-()
LIMIT {max_nodes} RETURN nodes(p) AS n, relationships(p) AS r
$$) AS (n agtype, r agtype)""" LIMIT {max_nodes}
$$) AS (n agtype, r agtype)"""
else:
query = f"""SELECT * FROM cypher('{self.graph_name}', $$
MATCH (node:base {{entity_id: "{strip_label}"}})
RETURN node AS n
$$) AS (n agtype)"""
results = await self._query(query) results = await self._query(query)