Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix: refine structure graph keyword search (#18181)

buua436c10371d9452b
diff --git a/api/apps/services/structure_graph_common.py b/api/apps/services/structure_graph_common.py
index 19dfbb9c2f..6fb80ef778 100644
--- a/api/apps/services/structure_graph_common.py
+++ b/api/apps/services/structure_graph_common.py
@@ -47,6 +47,10 @@ GRAPH_TOP_ENTITIES = 256
# Keyword search needs a small, relevant candidate set; the larger sampling
# cap above is intended for rendering an entire large graph bucket.
GRAPH_KEYWORD_CANDIDATES = 16
+# Semantic fallback is intentionally singular. KNN is only used after exact
+# name and BM25 lookup fail; returning several approximate tree nodes creates
+# unrelated sibling branches in an otherwise focused path response.
+GRAPH_KEYWORD_KNN_CANDIDATES = 1
# Upper bound on the relation / neighbor-entity expansion so a hub node can't
# blow up the response.
GRAPH_EXPANSION_CAP = 4096
@@ -383,6 +387,7 @@ async def keyword_subgraph(
``knowledge_graph_kwd``).
"""
from common.doc_store.doc_store_base import MatchDenseExpr, MatchTextExpr
+ from rag.advanced_rag.knowlege_compile._common import tokenize_for_search
excluded_doc_ids = excluded_doc_ids or set()
@@ -408,17 +413,32 @@ async def keyword_subgraph(
terms = [term for term in query.split() if term]
return bool(terms) and all(term in name for term in terms)
- # Entity names are identifiers in the graph. Prefer lexical matching so
- # an exact title/entity name wins over a semantically similar row such as
- # a navigation or summary record.
- text_query = re.sub(r"[ :|\r\n\t,,。??/`!!&^%()\[\]{}<>*~'\"\\=]+", " ", str(keywords)).strip()
+ # Entity names are identifiers in the graph. Check the exact normalized
+ # name first: BM25 searches the entity description and may miss a stored
+ # name even when the query equals it, which would otherwise trigger KNN
+ # and return an approximate result. Partial-name queries
+ # continue through BM25 so they can intentionally return multiple nodes.
+ text_query = re.sub(r"[ :|\r\n\t,,。??/`!!&^%()\[\]{}<>*~'\"\\=]+", " ", str(keywords or "")).strip()
candidates = []
- if text_query:
+ exact_name = str(keywords or "").strip().lower()
+ if exact_name:
+ exact_map, _ = await graph_search(
+ index_name,
+ kb_id,
+ top_fields,
+ dict(base_entity_condition, name_kwd=[exact_name]),
+ OrderByExpr(),
+ GRAPH_KEYWORD_CANDIDATES,
+ )
+ candidates = _valid_top_nodes(exact_map)
+ if text_query and not candidates:
+ coarse_query, fine_query = tokenize_for_search(text_query)
+ tokenized_query = " ".join(dict.fromkeys(f"{coarse_query} {fine_query}".split())) or text_query
text_expr = MatchTextExpr(
["content_ltks^10", "content_sm_ltks"],
- text_query,
+ tokenized_query,
GRAPH_KEYWORD_CANDIDATES,
- {"original_query": keywords},
+ {"original_query": tokenized_query},
)
top_map, _ = await graph_search(index_name, kb_id, top_fields, base_entity_condition, OrderByExpr(), GRAPH_KEYWORD_CANDIDATES, match_expressions=[text_expr])
candidates = [(row, node) for row, node in _valid_top_nodes(top_map) if _name_matches_query(node, text_query)]
@@ -447,10 +467,10 @@ async def keyword_subgraph(
embedding_data=vec,
embedding_data_type="float",
distance_type="cosine",
- topn=GRAPH_KEYWORD_CANDIDATES,
+ topn=GRAPH_KEYWORD_KNN_CANDIDATES,
extra_options={"similarity": 0.3},
)
- top_map, _ = await graph_search(index_name, kb_id, top_fields, base_entity_condition, OrderByExpr(), GRAPH_KEYWORD_CANDIDATES, match_expressions=[match_expr])
+ top_map, _ = await graph_search(index_name, kb_id, top_fields, base_entity_condition, OrderByExpr(), GRAPH_KEYWORD_KNN_CANDIDATES, match_expressions=[match_expr])
candidates = _valid_top_nodes(top_map)
if not candidates:
@@ -508,43 +528,66 @@ async def keyword_subgraph(
# Tree-like structures encode hierarchy as parent -> child. A keyword may
# hit a leaf, but the UI needs the complete path back to the root in order
- # to render that leaf in context. Walk the incoming edges until no new
- # ancestor is found (or the global expansion cap is reached).
+ # to render that leaf in context. Resolve the path in this template one
+ # endpoint at a time. Document-level relation endpoints may
+ # retain their original case while dataset-level endpoints are lowercased;
+ # querying one spelling at a time also avoids store-specific multi-value
+ # keyword-filter semantics.
+ tree_entities: list[dict] = []
if structure_kind in {"tree", "page_index", "pageindex"} and len(relations) < GRAPH_EXPANSION_CAP:
- ancestor_frontier = set(matched_names)
+ ancestor_frontier = {str(node.get("name") or "").strip().lower(): str(node.get("name") or "").strip() for node in matched_nodes if str(node.get("name") or "").strip()}
seen_ancestors = set(matched_names)
+ ancestor_names: dict[str, str] = {}
while ancestor_frontier and len(relations) < GRAPH_EXPANSION_CAP:
- next_frontier: set[str] = set()
- rel_map, _ = await graph_search(
+ next_frontier: dict[str, str] = {}
+ for child_name in ancestor_frontier.values():
+ for child_term in _endpoint_terms(child_name):
+ rel_map, _ = await graph_search(
+ index_name,
+ kb_id,
+ GRAPH_RELATION_FIELDS,
+ dict(scope, knowledge_graph_kwd=["relation"], to_entity_kwd=[child_term]),
+ OrderByExpr(),
+ GRAPH_EXPANSION_CAP - len(relations),
+ )
+ for row in rel_map.values():
+ if not _row_has_enabled_source(row, excluded_doc_ids):
+ continue
+ edge = project_relation(row)
+ if not edge:
+ continue
+ key = (edge.get("from", ""), edge.get("to", ""), edge.get("type", ""))
+ if key in seen_rel:
+ continue
+ seen_rel.add(key)
+ relations.append(edge)
+ parent_name = str(edge.get("from") or "").strip()
+ parent = parent_name.lower()
+ if parent and parent not in seen_ancestors:
+ seen_ancestors.add(parent)
+ next_frontier[parent] = parent_name
+ ancestor_names[parent] = parent_name
+ if len(relations) >= GRAPH_EXPANSION_CAP:
+ break
+ if len(relations) >= GRAPH_EXPANSION_CAP:
+ break
+ if len(relations) >= GRAPH_EXPANSION_CAP:
+ break
+ ancestor_frontier = next_frontier
+ neighbor_names_lower.update(seen_ancestors - matched_names)
+ for name in ancestor_names:
+ entity_map, _ = await graph_search(
index_name,
kb_id,
- GRAPH_RELATION_FIELDS,
- dict(scope, knowledge_graph_kwd=["relation"], to_entity_kwd=sorted(ancestor_frontier)),
+ GRAPH_ENTITY_FIELDS,
+ dict(scope, knowledge_graph_kwd=["entity"], name_kwd=[name]),
OrderByExpr(),
- GRAPH_EXPANSION_CAP - len(relations),
+ GRAPH_EXPANSION_CAP,
)
- for row in rel_map.values():
- if not _row_has_enabled_source(row, excluded_doc_ids):
- continue
- edge = project_relation(row)
- if not edge:
- continue
- key = (edge.get("from", ""), edge.get("to", ""), edge.get("type", ""))
- if key in seen_rel:
- continue
- seen_rel.add(key)
- relations.append(edge)
- parent = str(edge.get("from") or "").strip().lower()
- if parent and parent not in seen_ancestors:
- seen_ancestors.add(parent)
- next_frontier.add(parent)
- if len(relations) >= GRAPH_EXPANSION_CAP:
- break
- ancestor_frontier = next_frontier
- neighbor_names_lower.update(next_frontier)
+ tree_entities.extend(n for n in (project_entity(row) for row in entity_map.values() if _row_has_enabled_source(row, excluded_doc_ids)) if n)
- entities = list(matched_nodes)
- if neighbor_names_lower:
+ entities = list(matched_nodes) + tree_entities
+ if neighbor_names_lower and structure_kind not in {"tree", "page_index", "pageindex"}:
nb_map, _ = await graph_search(index_name, kb_id, GRAPH_ENTITY_FIELDS, dict(scope, knowledge_graph_kwd=["entity"], name_kwd=sorted(neighbor_names_lower)), OrderByExpr(), GRAPH_EXPANSION_CAP)
entities.extend(n for n in (project_entity(r) for r in nb_map.values() if _row_has_enabled_source(r, excluded_doc_ids)) if n)
diff --git a/test/unit_test/api/apps/services/test_structure_graph_common.py b/test/unit_test/api/apps/services/test_structure_graph_common.py
new file mode 100644
index 0000000000..6f95483124
--- /dev/null
+++ b/test/unit_test/api/apps/services/test_structure_graph_common.py
@@ -0,0 +1,217 @@
+#
+# Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import asyncio
+import importlib.util
+import json
+import sys
+from pathlib import Path
+from types import ModuleType, SimpleNamespace
+
+
+def _load_module(monkeypatch):
+ class OrderByExpr:
+ pass
+
+ class MatchTextExpr:
+ def __init__(self, fields, matching_text, topn, extra_options=None):
+ self.fields = fields
+ self.matching_text = matching_text
+ self.topn = topn
+ self.extra_options = extra_options or {}
+
+ class MatchDenseExpr:
+ def __init__(self, *_args, **kwargs):
+ self.topn = kwargs.get("topn")
+
+ async def thread_pool_exec(func, *args, **kwargs):
+ return func(*args, **kwargs)
+
+ common = ModuleType("common")
+ common.settings = SimpleNamespace()
+ doc_store_base = ModuleType("common.doc_store.doc_store_base")
+ doc_store_base.OrderByExpr = OrderByExpr
+ doc_store_base.MatchTextExpr = MatchTextExpr
+ doc_store_base.MatchDenseExpr = MatchDenseExpr
+ misc_utils = ModuleType("common.misc_utils")
+ misc_utils.thread_pool_exec = thread_pool_exec
+ structure = ModuleType("rag.advanced_rag.knowlege_compile.structure")
+ structure._struct_graph_entity = lambda payload, _chunk_ids: dict(payload)
+ structure._struct_graph_relation = lambda payload: dict(payload) if payload.get("from") and payload.get("to") else None
+ compile_common = ModuleType("rag.advanced_rag.knowlege_compile._common")
+ compile_common.tokenize_for_search = lambda text: (f"coarse:{text}", f"fine:{text}")
+
+ monkeypatch.setitem(sys.modules, "common", common)
+ monkeypatch.setitem(sys.modules, "common.doc_store", ModuleType("common.doc_store"))
+ monkeypatch.setitem(sys.modules, "common.doc_store.doc_store_base", doc_store_base)
+ monkeypatch.setitem(sys.modules, "common.misc_utils", misc_utils)
+ monkeypatch.setitem(sys.modules, "rag", ModuleType("rag"))
+ monkeypatch.setitem(sys.modules, "rag.advanced_rag", ModuleType("rag.advanced_rag"))
+ monkeypatch.setitem(sys.modules, "rag.advanced_rag.knowlege_compile", ModuleType("rag.advanced_rag.knowlege_compile"))
+ monkeypatch.setitem(sys.modules, "rag.advanced_rag.knowlege_compile._common", compile_common)
+ monkeypatch.setitem(sys.modules, "rag.advanced_rag.knowlege_compile.structure", structure)
+
+ path = Path(__file__).parents[5] / "api/apps/services/structure_graph_common.py"
+ spec = importlib.util.spec_from_file_location("structure_graph_common_under_test", path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+def _entity(name, entity_type="tree_node"):
+ return {
+ "knowledge_graph_kwd": "entity",
+ "content_with_weight": json.dumps({"name": name, "type": entity_type}),
+ "name_kwd": name.lower(),
+ }
+
+
+def _relation(parent, child):
+ return {
+ "knowledge_graph_kwd": "relation",
+ "content_with_weight": json.dumps({"from": parent, "to": child, "type": "parent_child"}),
+ "from_entity_kwd": parent,
+ "to_entity_kwd": child,
+ }
+
+
+def test_tree_keyword_subgraph_returns_only_match_and_ancestor_path(monkeypatch):
+ module = _load_module(monkeypatch)
+ leaf = _entity("Leaf")
+ fallback_expressions = []
+ bucket_rows = [
+ _entity("Root", "title"),
+ _entity("Parent"),
+ leaf,
+ _entity("Child"),
+ _relation("ROOT", "Parent"),
+ _relation("Parent", "leaf"),
+ _relation("Leaf", "Child"),
+ ]
+
+ async def graph_search(_index, _kb_id, _fields, condition, _order, _limit, match_expressions=None, offset=0):
+ if match_expressions:
+ fallback_expressions.extend(match_expressions)
+ return {"leaf": leaf}, 1
+ kind = condition["knowledge_graph_kwd"]
+ if kind == ["relation"]:
+ child = condition["to_entity_kwd"][0]
+ rows = [row for row in bucket_rows if row["knowledge_graph_kwd"] == "relation" and row["to_entity_kwd"] == child]
+ else:
+ assert kind == ["entity"]
+ name = condition["name_kwd"][0].lower()
+ rows = [row for row in bucket_rows if row["knowledge_graph_kwd"] == "entity" and row["name_kwd"] == name]
+ return {str(i): row for i, row in enumerate(rows)}, len(rows)
+
+ module.graph_search = graph_search
+
+ def scope_for_template(_row):
+ return {"template_id": "tree-1", "kind": "tree"}, {"doc_id": ["doc-1"], "compilation_template_ids": ["tree-1"]}
+
+ bucket, entities, relations = asyncio.run(
+ module.keyword_subgraph(
+ "index",
+ "kb-1",
+ SimpleNamespace(),
+ {"doc_id": ["doc-1"], "knowledge_graph_kwd": ["entity"]},
+ "Leaf",
+ scope_for_template,
+ )
+ )
+
+ assert bucket["template_id"] == "tree-1"
+ assert {entity["name"] for entity in entities} == {"Root", "Parent", "Leaf"}
+ assert {(relation["from"], relation["to"]) for relation in relations} == {("Root", "Parent"), ("Parent", "Leaf")}
+ assert fallback_expressions == []
+
+
+def test_keyword_subgraph_tokenizes_query_before_bm25(monkeypatch):
+ module = _load_module(monkeypatch)
+ matched = _entity("桃园结义初平黄巾")
+ text_expressions = []
+
+ async def graph_search(_index, _kb_id, _fields, condition, _order, _limit, match_expressions=None, offset=0):
+ if match_expressions:
+ text_expressions.extend(match_expressions)
+ return {"matched": matched}, 1
+ if condition["knowledge_graph_kwd"] == ["entity"] and "name_kwd" in condition:
+ return {}, 0
+ return {}, 0
+
+ module.graph_search = graph_search
+
+ bucket, entities, relations = asyncio.run(
+ module.keyword_subgraph(
+ "index",
+ "kb-1",
+ SimpleNamespace(),
+ {"doc_id": ["doc-1"], "knowledge_graph_kwd": ["entity"]},
+ "桃园结义",
+ lambda _row: ({"template_id": "tree-1", "kind": "tree"}, {"doc_id": ["doc-1"], "compilation_template_ids": ["tree-1"]}),
+ )
+ )
+
+ assert bucket["template_id"] == "tree-1"
+ assert [entity["name"] for entity in entities] == ["桃园结义初平黄巾"]
+ assert relations == []
+ assert len(text_expressions) == 1
+ assert text_expressions[0].matching_text == "coarse:桃园结义 fine:桃园结义"
+ assert text_expressions[0].extra_options["original_query"] == text_expressions[0].matching_text
+
+
+def test_keyword_subgraph_limits_knn_fallback_to_one_candidate(monkeypatch):
+ module = _load_module(monkeypatch)
+ matched = _entity("Semantic leaf")
+ root = _entity("Root", "title")
+ parent = _entity("Parent")
+ relation_rows = [_relation("Root", "Parent"), _relation("Parent", "Semantic leaf")]
+ dense_expressions = []
+ search_limits = []
+
+ async def graph_search(_index, _kb_id, _fields, condition, _order, limit, match_expressions=None, offset=0):
+ if match_expressions and isinstance(match_expressions[0], sys.modules["common.doc_store.doc_store_base"].MatchDenseExpr):
+ dense_expressions.extend(match_expressions)
+ search_limits.append(limit)
+ return {"matched": matched}, 1
+ if condition["knowledge_graph_kwd"] == ["relation"]:
+ child = condition["to_entity_kwd"][0]
+ rows = [row for row in relation_rows if row["to_entity_kwd"] == child]
+ return {str(i): row for i, row in enumerate(rows)}, len(rows)
+ if condition["knowledge_graph_kwd"] == ["entity"] and "name_kwd" in condition:
+ name = condition["name_kwd"][0]
+ rows = [entity for entity in (root, parent) if entity["name_kwd"] == name]
+ return {str(i): row for i, row in enumerate(rows)}, len(rows)
+ return {}, 0
+
+ module.graph_search = graph_search
+ embedding = SimpleNamespace(encode_queries=lambda _query: ([0.1, 0.2], 2))
+
+ bucket, entities, relations = asyncio.run(
+ module.keyword_subgraph(
+ "index",
+ "kb-1",
+ embedding,
+ {"doc_id": ["doc-1"], "knowledge_graph_kwd": ["entity"]},
+ "unmatched",
+ lambda _row: ({"template_id": "tree-1", "kind": "tree"}, {"doc_id": ["doc-1"], "compilation_template_ids": ["tree-1"]}),
+ )
+ )
+
+ assert bucket["template_id"] == "tree-1"
+ assert {entity["name"] for entity in entities} == {"Root", "Parent", "Semantic leaf"}
+ assert {(relation["from"], relation["to"]) for relation in relations} == {("Root", "Parent"), ("Parent", "Semantic leaf")}
+ assert dense_expressions[0].topn == 1
+ assert search_limits == [1]