Repository navigation
fix: add search keywords and filter for datasets-search - #16550
Conversation
📝 WalkthroughWalkthroughThis PR adds option-driven document listing and metadata filtering across DAO, service, and handler layers. It also updates project root discovery to check a new environment override and scan upward for ChangesDocument listing filters and metadata
Project root lookup
Estimated code review effort: 4 (Complex) | ~60 minutes Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
internal/handler/document.go (1)
589-634: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMinor:
queryValues(c, "run", "run_status")computed twice.Lines 599 and 600 both re-invoke
queryValues(c, "run", "run_status"). Not incorrect, just slightly wasteful; could be hoisted into a local variable.🤖 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 `@internal/handler/document.go` around lines 589 - 634, The run-status query parameters in parseDocumentListOptions are being fetched twice via queryValues(c, "run", "run_status"), which is unnecessary. Hoist that call into a local variable inside parseDocumentListOptions, then reuse it for normalizeRunStatusFilter and the empty-filter validation to keep the logic the same but avoid duplicate work.internal/dao/document.go (1)
156-204: 🚀 Performance & Scalability | 🔵 Trivial | ⚖️ Poor tradeoffFull-scan Go-side aggregation instead of SQL-side
GROUP BY/COUNT.
GetFilterByKBIDandListIDsByKBIDWithOptionsfetch every matching row (noLIMIT) and aggregate suffix/run counts or IDs in Go. For large datasets this is O(n) row transfer + processing on every filter/metadata-narrowing request (called fromGetDocumentFiltersByDatasetIDandapplyDocumentMetadataFilter, i.e., on the hot path oftype=filterand metadata-filtered listings). Consider pushing the counting to SQL (GROUP BY suffix,GROUP BY run) to avoid transferring/holding full row sets in memory.🤖 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 `@internal/dao/document.go` around lines 156 - 204, `GetFilterByKBID` and `ListIDsByKBIDWithOptions` are doing full-row scans and aggregating in Go on a hot path, which is expensive for large datasets. Update `DocumentDAO.GetFilterByKBID` to compute `suffix` and `run_status` counts in SQL with `GROUP BY`/`COUNT`, and change `ListIDsByKBIDWithOptions` to avoid loading all matching rows into memory if possible by narrowing the query or using a more direct ID fetch path. Keep the existing `applyDocumentListFilters` and DAO method signatures, but shift the heavy aggregation work out of Go.
🤖 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 `@internal/handler/document.go`:
- Around line 636-655: The applyDocumentMetadataFilter path is leaking internal
error text from GetMetadataByKBs directly to API clients. Update the error
handling in DocumentHandler.applyDocumentMetadataFilter so the returned message
is a generic client-safe string, consistent with the
ListDocumentIDsByDatasetIDWithOptions branch, while keeping the detailed error
only in internal logs if needed.
In `@internal/utility/path.go`:
- Around line 26-30: The GetProjectRoot helper is treating RAGFLOW_CONF_DIR as
the project root, which conflicts with how callers build conf paths. Update
internal/utility/path.go and the downstream joins in symbols like
GetProjectRoot, client.go, and chunk.go so the environment variable clearly
represents either the project root or the conf directory, and ensure the final
path construction does not append "conf" twice when an operator sets the
override.
---
Nitpick comments:
In `@internal/dao/document.go`:
- Around line 156-204: `GetFilterByKBID` and `ListIDsByKBIDWithOptions` are
doing full-row scans and aggregating in Go on a hot path, which is expensive for
large datasets. Update `DocumentDAO.GetFilterByKBID` to compute `suffix` and
`run_status` counts in SQL with `GROUP BY`/`COUNT`, and change
`ListIDsByKBIDWithOptions` to avoid loading all matching rows into memory if
possible by narrowing the query or using a more direct ID fetch path. Keep the
existing `applyDocumentListFilters` and DAO method signatures, but shift the
heavy aggregation work out of Go.
In `@internal/handler/document.go`:
- Around line 589-634: The run-status query parameters in
parseDocumentListOptions are being fetched twice via queryValues(c, "run",
"run_status"), which is unnecessary. Hoist that call into a local variable
inside parseDocumentListOptions, then reuse it for normalizeRunStatusFilter and
the empty-filter validation to keep the logic the same but avoid duplicate work.
🪄 Autofix (Beta)
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
Run ID: 9cb1c255-18fe-42f9-be20-d971429ee5fd
📒 Files selected for processing (5)
internal/dao/document.gointernal/handler/document.gointernal/handler/document_test.gointernal/service/document.gointernal/utility/path.go
| func (h *DocumentHandler) applyDocumentMetadataFilter(c *gin.Context, opts dao.DocumentListOptions) (dao.DocumentListOptions, string) { | ||
| metadata, err := parseMetadataQuery(c.Request.URL.Query()) | ||
| if err != nil { | ||
| return opts, err.Error() | ||
| } | ||
| returnEmptyMetadata := strings.ToLower(strings.TrimSpace(c.Query("return_empty_metadata"))) == "true" | ||
| if !returnEmptyMetadata && len(metadata) == 0 { | ||
| return opts, "" | ||
| } | ||
|
|
||
| candidateIDs, err := h.documentService.ListDocumentIDsByDatasetIDWithOptions(opts) | ||
| if err != nil { | ||
| return opts, "failed to get documents" | ||
| } | ||
| candidateSet := stringSet(candidateIDs) | ||
|
|
||
| metadataByKey, err := h.documentService.GetMetadataByKBs([]string{opts.KbID}) | ||
| if err != nil { | ||
| return opts, err.Error() | ||
| } |
There was a problem hiding this comment.
🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win
Avoid leaking raw internal error text to API clients.
Line 654 returns err.Error() from GetMetadataByKBs directly as the client-facing message, unlike the sibling error path at Line 648 which uses a generic "failed to get documents" string. This risks exposing internal implementation details (DB/service error internals) to API consumers.
🛡️ Proposed fix
metadataByKey, err := h.documentService.GetMetadataByKBs([]string{opts.KbID})
if err != nil {
- return opts, err.Error()
+ return opts, "failed to get document metadata"
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| func (h *DocumentHandler) applyDocumentMetadataFilter(c *gin.Context, opts dao.DocumentListOptions) (dao.DocumentListOptions, string) { | |
| metadata, err := parseMetadataQuery(c.Request.URL.Query()) | |
| if err != nil { | |
| return opts, err.Error() | |
| } | |
| returnEmptyMetadata := strings.ToLower(strings.TrimSpace(c.Query("return_empty_metadata"))) == "true" | |
| if !returnEmptyMetadata && len(metadata) == 0 { | |
| return opts, "" | |
| } | |
| candidateIDs, err := h.documentService.ListDocumentIDsByDatasetIDWithOptions(opts) | |
| if err != nil { | |
| return opts, "failed to get documents" | |
| } | |
| candidateSet := stringSet(candidateIDs) | |
| metadataByKey, err := h.documentService.GetMetadataByKBs([]string{opts.KbID}) | |
| if err != nil { | |
| return opts, err.Error() | |
| } | |
| func (h *DocumentHandler) applyDocumentMetadataFilter(c *gin.Context, opts dao.DocumentListOptions) (dao.DocumentListOptions, string) { | |
| metadata, err := parseMetadataQuery(c.Request.URL.Query()) | |
| if err != nil { | |
| return opts, err.Error() | |
| } | |
| returnEmptyMetadata := strings.ToLower(strings.TrimSpace(c.Query("return_empty_metadata"))) == "true" | |
| if !returnEmptyMetadata && len(metadata) == 0 { | |
| return opts, "" | |
| } | |
| candidateIDs, err := h.documentService.ListDocumentIDsByDatasetIDWithOptions(opts) | |
| if err != nil { | |
| return opts, "failed to get documents" | |
| } | |
| candidateSet := stringSet(candidateIDs) | |
| metadataByKey, err := h.documentService.GetMetadataByKBs([]string{opts.KbID}) | |
| if err != nil { | |
| return opts, "failed to get document metadata" | |
| } |
🤖 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 `@internal/handler/document.go` around lines 636 - 655, The
applyDocumentMetadataFilter path is leaking internal error text from
GetMetadataByKBs directly to API clients. Update the error handling in
DocumentHandler.applyDocumentMetadataFilter so the returned message is a generic
client-safe string, consistent with the ListDocumentIDsByDatasetIDWithOptions
branch, while keeping the detailed error only in internal logs if needed.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/engine/infinity/sql_test.go (1)
336-338: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueStale comment: says "temp dir's parent" but code uses
diritself.The comment states RAG_PROJECT_BASE is set to the temp dir's parent, but line 338 sets it to
dirdirectly, andconf/is created underdir(line 341) — matching<base>/conf/<filename>with base=dir, not dir's parent.✏️ Suggested comment fix
- // Set RAG_PROJECT_BASE to the temp dir's parent so loadFieldMapping + // Set RAG_PROJECT_BASE to the temp dir itself so loadFieldMapping // finds the file at <base>/conf/<filename>.🤖 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 `@internal/engine/infinity/sql_test.go` around lines 336 - 338, Update the stale comment near the RAG_PROJECT_BASE setup in sql_test.go so it accurately describes what the test does: the base is set to dir itself, not the temp dir’s parent. Keep the comment aligned with loadFieldMapping and the conf directory creation logic in this test, and adjust the wording around the existing t.Setenv call accordingly.
🤖 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 `@internal/engine/infinity/sql_test.go`:
- Line 338: The test setup in sql_test.go relies on RAG_PROJECT_BASE, but
GetProjectRoot checks RAGFLOW_CONF_DIR first, so these cases can be overridden
by a preexisting environment variable and become flaky. Update the relevant test
setup around the affected test functions to explicitly clear RAGFLOW_CONF_DIR
before calling GetProjectRoot, alongside the existing RAG_PROJECT_BASE temp-dir
setup, so the test always uses the intended temporary directory.
---
Nitpick comments:
In `@internal/engine/infinity/sql_test.go`:
- Around line 336-338: Update the stale comment near the RAG_PROJECT_BASE setup
in sql_test.go so it accurately describes what the test does: the base is set to
dir itself, not the temp dir’s parent. Keep the comment aligned with
loadFieldMapping and the conf directory creation logic in this test, and adjust
the wording around the existing t.Setenv call accordingly.
🪄 Autofix (Beta)
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
Run ID: 5ce67450-c653-4359-ae55-cb67ba5fc73a
📒 Files selected for processing (1)
internal/engine/infinity/sql_test.go
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16550 +/- ##
==========================================
- Coverage 94.56% 93.16% -1.40%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 668 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
internal/dao/document.go (3)
195-200: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winReturn distinct document IDs from the join.
This joined query can return duplicate IDs if a document has multiple
file2documentrows. Downstream metadata filtering useslen(docIDs), so duplicates can inflateempty_metadatacounts.Proposed fix
query := DB.Table("document"). - Select("document.id"). + Select("DISTINCT document.id"). Joins("JOIN file2document ON file2document.document_id = document.id"). Joins("JOIN file ON file.id = file2document.file_id")🤖 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 `@internal/dao/document.go` around lines 195 - 200, The joined query in document DAO can return duplicate document IDs when a document has multiple file2document rows, which affects downstream filtering that relies on len(docIDs). Update the query built in the document list path to return distinct document.id values before Scan, keeping the existing joins and applyDocumentListFilters flow intact so the IDs slice contains unique documents only.
215-216: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winEscape LIKE metacharacters in keyword search.
%and_in user input are treated as wildcards, so searching for those literal characters broadens results unexpectedly.Proposed fix
- if strings.TrimSpace(opts.Keywords) != "" { - query = query.Where("LOWER("+column("name")+") LIKE ?", "%"+strings.ToLower(strings.TrimSpace(opts.Keywords))+"%") + if keyword := strings.ToLower(strings.TrimSpace(opts.Keywords)); keyword != "" { + keyword = strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(keyword) + query = query.Where("LOWER("+column("name")+") LIKE ? ESCAPE '\\'", "%"+keyword+"%") }🤖 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 `@internal/dao/document.go` around lines 215 - 216, The keyword filter in document search is treating user input as a raw LIKE pattern, so literal % and _ characters act as wildcards; update the keyword handling in the document query builder around the opts.Keywords branch to escape LIKE metacharacters before passing the argument to query.Where. Keep the existing LOWER(column("name")) matching behavior, but ensure the search term is sanitized/escaped consistently so literal special characters are matched as text rather than expanding the result set.
134-137: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winBuild
totalfrom the same joined relation as the list query.
listQueryexcludes rows without matchingfile2document/filerecords, butcountQuerycounts alldocumentrows in the KB. This can make pagination totals and empty states disagree with the returned docs.Proposed fix
- countQuery := applyDocumentListFilters(DB.Model(&entity.Document{}), opts, false) + countQuery := DB.Table("document"). + Joins("JOIN file2document ON file2document.document_id = document.id"). + Joins("JOIN file ON file.id = file2document.file_id") + countQuery = applyDocumentListFilters(countQuery, opts, true) - if err := countQuery.Count(&total).Error; err != nil { + if err := countQuery.Distinct("document.id").Count(&total).Error; err != nil { return nil, 0, err }🤖 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 `@internal/dao/document.go` around lines 134 - 137, The document listing logic is counting a different result set than it returns: apply the same joined/filtering path used by listQuery when building total so rows without matching file2document/file records are excluded from count as well. Update the countQuery in applyDocumentListFilters/useDocumentListFilters flow to mirror the joined relation and filters used for the list query, rather than counting DB.Model(&entity.Document{}) directly, so pagination totals and returned docs stay consistent.
🤖 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.
Outside diff comments:
In `@internal/dao/document.go`:
- Around line 195-200: The joined query in document DAO can return duplicate
document IDs when a document has multiple file2document rows, which affects
downstream filtering that relies on len(docIDs). Update the query built in the
document list path to return distinct document.id values before Scan, keeping
the existing joins and applyDocumentListFilters flow intact so the IDs slice
contains unique documents only.
- Around line 215-216: The keyword filter in document search is treating user
input as a raw LIKE pattern, so literal % and _ characters act as wildcards;
update the keyword handling in the document query builder around the
opts.Keywords branch to escape LIKE metacharacters before passing the argument
to query.Where. Keep the existing LOWER(column("name")) matching behavior, but
ensure the search term is sanitized/escaped consistently so literal special
characters are matched as text rather than expanding the result set.
- Around line 134-137: The document listing logic is counting a different result
set than it returns: apply the same joined/filtering path used by listQuery when
building total so rows without matching file2document/file records are excluded
from count as well. Update the countQuery in
applyDocumentListFilters/useDocumentListFilters flow to mirror the joined
relation and filters used for the list query, rather than counting
DB.Model(&entity.Document{}) directly, so pagination totals and returned docs
stay consistent.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 3420174e-f5c6-4b50-9491-f91ce8185080
📒 Files selected for processing (4)
internal/dao/document.gointernal/handler/document.gointernal/handler/document_test.gointernal/service/document.go
🚧 Files skipped from review as they are similar to previous changes (3)
- internal/handler/document_test.go
- internal/handler/document.go
- internal/service/document.go
Removed environment variable check for RAGFLOW_CONF_DIR and simplified project root retrieval logic.
|
LGTM |
Summary
As title:
main fix:
https://github.com/Haruko386/ragflow/blame/6618c023638f55dfd65593557d4728b315e3ade0/internal/dao/document.go#L106