Skip to content

fix: improve structure keyword search - #18055

Merged
wangq8 merged 2 commits into
infiniflow:mainfrom
buua436:b154
Aug 11, 2026
Merged

wangq8 merged 2 commits into
infiniflow:mainfrom
buua436:b154

Conversation

@buua436

@buua436 buua436 commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Improve keyword search for document and dataset structure graphs.

  • Prefer BM25 text matching on entity search fields.
  • Fall back to KNN semantic matching when BM25 has no valid result.
  • Return multiple matched entities instead of only one.
  • For tree and page_index, return matched nodes together with their parent path, without unrelated sibling or child nodes.
  • Add logs to distinguish BM25 matches from KNN fallback results.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Aug 10, 2026
@buua436 buua436 added ci Continue Integration and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Aug 10, 2026
@dosubot dosubot Bot added the 🐞 bug Something isn't working, pull request that fix bug. label Aug 10, 2026
@coderabbitai

coderabbitai Bot commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 830765a0-aa58-4e04-8077-b2ffbba32796

📥 Commits

Reviewing files that changed from the base of the PR and between 2ae93ac and 6f35339.

📒 Files selected for processing (2)
  • api/apps/services/dataset_api_service.py
  • api/apps/services/structure_graph_common.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • api/apps/services/dataset_api_service.py
  • api/apps/services/structure_graph_common.py

📝 Walkthrough

Walkthrough

Keyword structure-graph retrieval now uses lexical entity-name matching with bounded KNN fallback. It returns subgraphs for multiple matched entities and applies structure-specific relation expansion.

Changes

Structure-graph keyword retrieval

Layer / File(s) Summary
Keyword candidate selection
api/apps/services/structure_graph_common.py, api/apps/services/dataset_api_service.py, api/apps/restful_apis/chunk_api.py
Keyword queries are normalized and matched with BM25. Invalid and excluded rows are filtered. Detail entities take priority over title entities. KNN provides a bounded fallback. Comments and docstrings describe the updated behavior.
Structure-aware subgraph expansion
api/apps/services/structure_graph_common.py
The method expands all matched entities. Non-tree structures include capped incoming and outgoing relations. Tree structures include ancestor paths and retain relations whose endpoints are returned.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant DatasetStructureAPI
  participant keyword_subgraph
  participant BM25
  participant KNNFallback
  participant StructureGraph
  DatasetStructureAPI->>keyword_subgraph: Submit normalized keyword query
  keyword_subgraph->>BM25: Match entity names
  BM25-->>keyword_subgraph: Return lexical candidates
  alt No lexical candidates
    keyword_subgraph->>KNNFallback: Retrieve bounded embedding candidates
    KNNFallback-->>keyword_subgraph: Return KNN candidates
  end
  keyword_subgraph->>StructureGraph: Expand matched entities and relations
  StructureGraph-->>DatasetStructureAPI: Return filtered subgraph
Loading

Possibly related PRs

Suggested labels: 🌈 python

Poem

A rabbit searched the graph at night,
BM25 matched names just right.
KNN waited when names were few,
Ancestor paths came hopping through.
Tidy subgraphs filled the den.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change to structure keyword search.
Description check ✅ Passed The description clearly explains the problem, key changes, and non-breaking bug-fix scope, although it uses a different heading than the template.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (3)
api/apps/services/structure_graph_common.py (3)

560-568: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Copy matched_nodes instead of aliasing it.

Line 560 binds entities to the same list object as matched_nodes. Line 563 then mutates that shared list. matched_nodes is not read after this point, so there is no current defect. A copy prevents a future reader from assuming matched_nodes still holds only the matches.

♻️ Proposed change
-    entities = matched_nodes
+    entities = list(matched_nodes)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/services/structure_graph_common.py` around lines 560 - 568,
Initialize entities as a copy of matched_nodes rather than assigning the same
list object, then preserve the existing neighbor extension and deduplication
flow.

420-435: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rename the exact_candidates log key.

The filter uses substring and all-terms containment, not exact matching. The key exact_candidates names the value incorrectly and will mislead log readers. Use matched_candidates.

The title-preference block at Lines 429-435 matches the stated PR objective and reads correctly.

♻️ Proposed change
-        "structure graph keyword BM25 (%s): query=%r total=%d returned=%d exact_candidates=%d names=%s",
+        "structure graph keyword BM25 (%s): query=%r total=%d returned=%d matched_candidates=%d names=%s",
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/services/structure_graph_common.py` around lines 420 - 435, Rename
the `exact_candidates` logging key in the structure graph BM25 log message to
`matched_candidates`, leaving the candidate filtering and title-preference logic
unchanged.

398-406: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider passing text_query as a parameter.

_name_matches_query reads text_query from the enclosing scope, but text_query is assigned later at Line 411. The call order is correct today, so there is no bug. An explicit parameter removes the ordering dependency and makes the helper easier to move or test.

♻️ Proposed refactor
-    def _name_matches_query(node):
+    def _name_matches_query(node, query):
         name = str(node.get("name") or "").strip().lower()
-        query = text_query.lower()
+        query = query.lower()
         if not name or not query:
             return False

Then update the call site:

-    candidates = [(row, node) for row, node in _valid_top_nodes(top_map) if _name_matches_query(node)]
+    candidates = [(row, node) for row, node in _valid_top_nodes(top_map) if _name_matches_query(node, text_query)]
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@api/apps/services/structure_graph_common.py` around lines 398 - 406, Update
_name_matches_query to accept text_query explicitly instead of reading it from
the enclosing scope, and pass the local text_query value at every call site.
Preserve the existing matching behavior while removing the helper’s dependency
on assignment order.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@api/apps/services/structure_graph_common.py`:
- Around line 370-381: The docstrings still describe the obsolete single-entity,
exact-match, 1-hop behavior. In
api/apps/services/structure_graph_common.py:370-381, update the keyword_subgraph
documentation to describe BM25 lexical search with name containment, matching
entities in the selected bucket, and full ancestor-path traversal for tree and
page_index kinds. In api/apps/services/dataset_api_service.py:1822-1822, replace
the single best-matching entity’s 1-hop description with wording that refers to
the matching entities’ subgraph.
- Around line 507-521: In the relation-processing loop, move the endpoint
collection for each appended edge before the GRAPH_EXPANSION_CAP check,
preserving the existing normalization and matched-name filtering. Ensure the
final edge that reaches the cap contributes both endpoints to
neighbor_names_lower before breaking, while retaining the current cap behavior
for subsequent processing.
- Around line 411-419: Update the keyword-search flow around text_query and
MatchTextExpr to skip BM25 when normalization produces an empty string. Log the
normalized-empty condition before falling back to KNN, and only construct
MatchTextExpr or call graph_search with match_expressions when text_query is
non-empty; preserve candidate filtering for non-empty queries.

---

Nitpick comments:
In `@api/apps/services/structure_graph_common.py`:
- Around line 560-568: Initialize entities as a copy of matched_nodes rather
than assigning the same list object, then preserve the existing neighbor
extension and deduplication flow.
- Around line 420-435: Rename the `exact_candidates` logging key in the
structure graph BM25 log message to `matched_candidates`, leaving the candidate
filtering and title-preference logic unchanged.
- Around line 398-406: Update _name_matches_query to accept text_query
explicitly instead of reading it from the enclosing scope, and pass the local
text_query value at every call site. Preserve the existing matching behavior
while removing the helper’s dependency on assignment order.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 29bf86c6-eb0e-486a-bb95-e70311d7cfca

📥 Commits

Reviewing files that changed from the base of the PR and between 6f9d158 and 2ae93ac.

📒 Files selected for processing (3)
  • api/apps/restful_apis/chunk_api.py
  • api/apps/services/dataset_api_service.py
  • api/apps/services/structure_graph_common.py

@codecov

codecov Bot commented Aug 10, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (4eaad55) to head (6f35339).
⚠️ Report is 38 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #18055   +/-   ##
=======================================
  Coverage   90.65%   90.65%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          650      650           
  Misses         39       39           
  Partials       28       28           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@buua436
buua436 requested a review from wangq8 August 10, 2026 11:03
@buua436 buua436 added ci Continue Integration and removed ci Continue Integration labels Aug 10, 2026

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this improvement! The BM25-first approach with KNN fallback is a solid architectural improvement — exact name matching makes a lot more sense for keyword search than relying solely on vector similarity. A few observations:

What looks good

  • Preferring BM25 over KNN for keyword search is the right priority — entity names are identifiers, not prose.
  • Returning multiple matched entities from the same bucket instead of only the top-1 is a clear UX improvement.
  • The tree/page_index ancestor path walk is well thought out — leaf matches shouldn't be returned without their parent context.
  • The logging additions to distinguish BM25 hits from KNN fallback are helpful for debugging.
  • Raising the KNN similarity threshold from 0.0 to 0.3 and lowering topn from 256 to 16 makes sense for a keyword-targeted query.

Questions / minor concerns

  1. Empty text_query edge case (line ~393): If keywords contains only special characters (e.g. "!!!"), re.sub(...).strip() produces an empty string, and MatchTextExpr would be called with an empty query. Could this cause unexpected behavior in Elasticsearch, or should there be a guard that falls through to KNN immediately when text_query is empty?

  2. Substring matching in _name_matches_query: The "query in name" check means a query like "cat" would match an entity named "catalog". For single-word queries this could produce noisy results. Is this intentional? A word-boundary or token-based match might be more precise for single-word queries while keeping the current behaviour for multi-word queries.

  3. detail_candidates filtering: When a keyword matches a title entity and no detail entities exist in the same bucket, the title match is preserved (which is correct). But when there are detail matches, the title is excluded from matched_nodes. In the tree/path-walk mode this is fine since the title will be pulled in as an ancestor — but for non-tree modes, could excluding the title entity cause a relevant match to be silently dropped?

None of these are blockers — the core logic is sound. Happy to approve once the empty-query edge case is addressed.

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Aug 11, 2026
@buua436 buua436 added ci Continue Integration and removed ci Continue Integration labels Aug 11, 2026
@wangq8
wangq8 merged commit 5fd6615 into infiniflow:main Aug 11, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants