Skip to content

fix: add search keywords and filter for datasets-search - #16550

Merged
xugangqiang merged 5 commits into
infiniflow:mainfrom
Haruko386:main
Jul 2, 2026
Merged

xugangqiang merged 5 commits into
infiniflow:mainfrom
Haruko386:main

Conversation

@Haruko386

Copy link
Copy Markdown
Member

@Haruko386 Haruko386 added 🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration labels Jul 2, 2026
@Haruko386
Haruko386 marked this pull request as draft July 2, 2026 03:17
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jul 2, 2026
@coderabbitai

coderabbitai Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This 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 go.mod.

Changes

Document listing filters and metadata

Layer / File(s) Summary
DAO options-based listing
internal/dao/document.go
Adds DocumentListOptions, options-based listing, filter aggregation, ID listing, and shared filter/order helpers.
Service options and metadata filters
internal/service/document.go
Passes keywords/options through listing and builds dataset-level filter payloads, including metadata counts.
Handler query parsing and metadata narrowing
internal/handler/document.go, internal/handler/document_test.go
Parses document query filters, narrows IDs by metadata, supports filter responses, and validates the new flows in tests.

Project root lookup

Layer / File(s) Summary
RAGFLOW_CONF_DIR and go.mod scan
internal/utility/path.go, internal/engine/infinity/sql_test.go
Adds RAGFLOW_CONF_DIR support and source-file-based upward scanning for go.mod, with tests updated to use isolated temp directories.

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

Possibly related PRs

Suggested labels: 🐞 bug

Suggested reviewers: yingfeng, yuzhichang, JinHai-CN

Poem

A rabbit hopped through filters bright,
And metadata gleamed in sight.
It found the root by go.mod trails,
Then bounded onward, leaving pails.
Hop hop! 🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: adding keyword search and filtering for dataset document listings.
Description check ✅ Passed The description includes the required Summary section and enough context, though it is brief and mostly points to screenshots.
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.

@Haruko386
Haruko386 marked this pull request as ready for review July 2, 2026 03:17

@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: 2

🧹 Nitpick comments (2)
internal/handler/document.go (1)

589-634: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Minor: 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 tradeoff

Full-scan Go-side aggregation instead of SQL-side GROUP BY/COUNT.

GetFilterByKBID and ListIDsByKBIDWithOptions fetch every matching row (no LIMIT) 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 from GetDocumentFiltersByDatasetID and applyDocumentMetadataFilter, i.e., on the hot path of type=filter and 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

📥 Commits

Reviewing files that changed from the base of the PR and between 27c9a09 and a8ebbe4.

📒 Files selected for processing (5)
  • internal/dao/document.go
  • internal/handler/document.go
  • internal/handler/document_test.go
  • internal/service/document.go
  • internal/utility/path.go

Comment on lines +636 to +655
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()
}

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.

🔒 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.

Suggested change
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.

Comment thread internal/utility/path.go Resolved

@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: 1

🧹 Nitpick comments (1)
internal/engine/infinity/sql_test.go (1)

336-338: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Stale comment: says "temp dir's parent" but code uses dir itself.

The comment states RAG_PROJECT_BASE is set to the temp dir's parent, but line 338 sets it to dir directly, and conf/ is created under dir (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

📥 Commits

Reviewing files that changed from the base of the PR and between a8ebbe4 and 6fbbb5d.

📒 Files selected for processing (1)
  • internal/engine/infinity/sql_test.go

Comment thread internal/engine/infinity/sql_test.go Resolved
@codecov

codecov Bot commented Jul 2, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (42a0faa) to head (6fbbb5d).
⚠️ Report is 17 commits behind head on main.

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.
📢 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.

@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.

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 win

Return distinct document IDs from the join.

This joined query can return duplicate IDs if a document has multiple file2document rows. Downstream metadata filtering uses len(docIDs), so duplicates can inflate empty_metadata counts.

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 win

Escape 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 win

Build total from the same joined relation as the list query.

listQuery excludes rows without matching file2document/file records, but countQuery counts all document rows 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

📥 Commits

Reviewing files that changed from the base of the PR and between 6fbbb5d and 33c11f9.

📒 Files selected for processing (4)
  • internal/dao/document.go
  • internal/handler/document.go
  • internal/handler/document_test.go
  • internal/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.
@xugangqiang

Copy link
Copy Markdown
Contributor

LGTM

@xugangqiang
xugangqiang merged commit 92e8eb5 into infiniflow:main Jul 2, 2026
3 checks passed
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 3, 2026
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 6, 2026
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:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants