Repository navigation
feat: add KG entity/relation/community search functions - #15689
Conversation
This change eliminates the duplicate filtering implementation between service.ApplyMetaFilter and common.MetaFilter by removing the applySingleCondition adapter layer and consolidating all operator handling into common.MetaFilter. Key changes: - Remove applySingleCondition (65 lines of inline switch logic) - ApplyMetaFilter now converts MetaFilterCondition to MetaCondition and delegates directly to common.MetaFilter once per filter set - Add filterSet: O(n+m) hash-map fast path for in/not in operators (replaces O(n*m) linear scan in matchValue) - Export NormalizeOperator from common for operator alias mapping (includes ==, !=, >=, <=, is, not is aliases) Bug fixes: - contains/not contains: restored case-insensitive matching (ToLower) - not in: restored case-insensitive matching (EqualFold) - != with date filter: non-date metadata values now correctly match the != operator (they are not equal to the date) - Added == to operatorMapping so both ParseAndConvert and convertToMetaCondition normalize it to = Performance: - in/not in: O(n*m) linear scan -> O(n+m) hash-map lookup via filterSet - = operator delegates to common.MetaFilter (O(n) iteration for correctness/case-insensitivity, matching Python behavior) Cleanup: - Removed 18 lines of dead code (matchValue's in/not in branches bypassed by filterOut delegation) - Fixed orphaned godoc comment for convertOperator (reordered with NormalizeOperator) - Fixed filterSet doc comment: removed incorrect 'matching EqualFold' claim - Completed convertToMetaCondition operator normalization comment Tests: 60 tests (24 service + 36 common), all passing. New tests cover ==, !=, >=, <=, >, <, empty, not empty operators through ApplyMetaFilter; <, <=, !=, not-in-empty-list through MetaFilter/filterSet. Co-Authored-By: Claude Opus 4.8 <[email protected]>
This file was accidentally included in the previous commit via git add internal/. The change was pre-existing in the working tree but unrelated to the metadata filter refactoring. Co-Authored-By: Claude Opus 4.8 <[email protected]>
When f.Value is "A,,B" or "A, ,B", strings.Split produces empty or whitespace-only entries. These are now filtered out after TrimSpace to prevent unintended matches against empty-string metadata values. Add 5 test cases: - InEmptyParts: A,,B produces [A B] - InOnlyWhitespaceParts: A, , ,B produces [A B] - InAllEmptyParts: ,,, produces [] - NotInEmptyParts: A,,B produces [A B] - InMixedSpaces: spaces around values preserve trimmed values Co-Authored-By: Claude Opus 4.8 <[email protected]>
…earch and tests - KGEntity, KGRelation, KGCommunityReport types with Parse*Chunks helpers - build*SearchRequest: pure request builders for entity/relation/community/type-samples - buildHybridExpr: shared dense+text+fusion expression construction - buildKGDenseExpr: wraps Embed() call for vector search - Search* functions: thin wrappers over DocEngine.Search + Parse*Chunks - Fix ParseKGTypeSamplesChunks stub: now parses JSON - Fix NhopEntityNames stub: now parses n_hop_with_weight JSON - 35 tests (pure function tests + mock integration tests) Co-Authored-By: Claude Opus 4.8 <[email protected]>
📝 WalkthroughWalkthroughThis PR refactors metadata filtering logic in the common layer (operator canonicalization, set-based ChangesMetadata Filter Refactoring
Knowledge Graph Search Service
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 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: 1
🧹 Nitpick comments (7)
internal/service/kg_search.go (4)
87-87: 💤 Low valueDocument rationale for fusion weights.
The hybrid fusion weights
0.05,0.95heavily favor text retrieval (95%) over dense embeddings (5%). If this is intentional for KG entity matching (where exact name matches should dominate), consider adding a brief comment explaining the rationale.🤖 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/service/kg_search.go` at line 87, Document why the fusion weights favor text retrieval by adding a brief inline comment next to the FusionParams declaration that sets map[string]interface{}{"weights": "0.05,0.95"} (in the code that builds the search parameters, i.e., the FusionParams field). Explain that 0.05/0.95 was chosen to prioritize exact/name-based text matches over dense embeddings for KG entity matching (or note any alternative rationale), and include a note about when/if these should be adjusted.
306-362: ⚡ Quick winConsider adding input validation.
The search functions don't validate inputs such as:
- Empty
kbIDsslice (would result in searching all KBs or an error)topN <= 0(could cause unexpected behavior in ES queries)- Nil
docEngine(would panic on.Search())Consider adding defensive checks at the entry points, especially for public API functions.
📝 Example validation for SearchKGEntities
func SearchKGEntities(ctx context.Context, docEngine engine.DocEngine, kbIDs []string, question string, embModel *modelModule.EmbeddingModel, topN int) ([]KGEntity, error) { + if len(kbIDs) == 0 { + return nil, fmt.Errorf("kbIDs cannot be empty") + } + if topN <= 0 { + return nil, fmt.Errorf("topN must be positive, got %d", topN) + } dense, err := buildKGDenseExpr(embModel, question, topN)🤖 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/service/kg_search.go` around lines 306 - 362, Add input validation to the public search functions (SearchKGEntities, SearchKGEntitiesByTypes, SearchKGRelations, SearchKGCommunityReports, SearchKGTypeSamples) to guard against nil docEngine, empty kbIDs, and invalid topN (<=0); return a descriptive error immediately if docEngine == nil, if len(kbIDs)==0 where a KB selection is required, or if topN <= 0 (or normalize topN to a sensible default) so downstream calls to docEngine.Search and build*Request functions cannot panic or send bad queries. Use the function names above to locate each entry point and apply the same checks consistently at the start of each function.
75-75: ⚡ Quick winConsider making similarity threshold configurable.
The similarity threshold of
0.3is hardcoded. Depending on the embedding model quality and use case, this threshold may need tuning. Consider parameterizing this value or documenting why 0.3 was chosen.🤖 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/service/kg_search.go` at line 75, The hardcoded similarity value (ExtraOptions: map[string]interface{}{"similarity": 0.3}) should be made configurable: introduce a named parameter or field (e.g., SimilarityThreshold float64) on the KG search config/constructor (such as the searcher struct or New... function used in kg_search.go), default it to 0.3 when unset, read an environment/config value or accept it from callers, and replace the hardcoded literal with that variable when building ExtraOptions so callers can tune the threshold without editing the code.
274-276: ⚡ Quick winPotential duplicate entities in type samples.
When multiple chunks contain the same type, entities are appended without deduplication. For example, if two chunks both have
"PERSON": ["Alice"], the result will contain["Alice", "Alice"]. If deduplication is needed, consider using a map or checking for duplicates before appending.🔧 Proposed fix to deduplicate entities
for typ, entities := range typeMap { + seen := make(map[string]bool) + for _, existing := range result[typ] { + seen[existing] = true + } + for _, e := range entities { + if !seen[e] { + result[typ] = append(result[typ], e) + seen[e] = true + } + } - result[typ] = append(result[typ], entities...) }🤖 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/service/kg_search.go` around lines 274 - 276, The merge loop appends entities from typeMap into result without deduplication, causing duplicate entity strings (e.g., "Alice") when the same type appears in multiple chunks; modify the merging code that iterates over typeMap (the for typ, entities := range typeMap loop) to deduplicate before appending by tracking seen entities per type (e.g., a map[string]map[string]struct{} or a map[string]set for each typ), only adding entities not already present in result[typ], and then convert back to the slice for result[typ]; ensure you update or reuse result[typ]’s existing entries when checking the seen set so no duplicates are introduced.internal/service/kg_search_test.go (2)
196-196: ⚡ Quick winFragile test: potential index out of bounds.
The test directly indexes
[0]without verifying thatParseKGEntityChunksreturned at least one entity. If the parsing logic changes or the input is modified, this will panic.🛡️ Proposed fix
func TestParseKGEntityChunks_ScoreFallback(t *testing.T) { chunks := []map[string]interface{}{{"entity_kwd": "Test", "score": 0.75}} - if ParseKGEntityChunks(chunks)[0].Similarity != 0.75 { - t.Error("expected 0.75 from score field") + entities := ParseKGEntityChunks(chunks) + if len(entities) != 1 || entities[0].Similarity != 0.75 { + t.Errorf("expected one entity with similarity 0.75, got %v", entities) } }🤖 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/service/kg_search_test.go` at line 196, The test indexing ParseKGEntityChunks(chunks)[0] is fragile and can panic if ParseKGEntityChunks returns an empty slice; change the test to first assign the result to a variable (e.g., entities := ParseKGEntityChunks(chunks)), assert or require that len(entities) > 0, and only then check entities[0].Similarity == 0.75 (use the existing testing/assert helper in kg_search_test.go to fail the test cleanly if empty).
221-221: ⚡ Quick winFragile test: potential index out of bounds.
Same issue as the entity test - directly indexing
[0]without length check.🛡️ Proposed fix
func TestParseKGRelationChunks_IntWeight(t *testing.T) { chunks := []map[string]interface{}{{"from_entity_kwd": "A", "to_entity_kwd": "B", "weight_int": 3}} - if ParseKGRelationChunks(chunks)[0].Weight != 3 { - t.Error("expected weight 3") + relations := ParseKGRelationChunks(chunks) + if len(relations) != 1 || relations[0].Weight != 3 { + t.Errorf("expected one relation with weight 3, got %v", relations) } }🤖 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/service/kg_search_test.go` at line 221, The test is indexing ParseKGRelationChunks(chunks)[0] without checking the slice length, risking an index out of bounds; update the test to first assert the returned slice has the expected length (e.g., len(ParseKGRelationChunks(chunks)) > 0 or compare to an exact expected length) before accessing element 0, or capture the result into a variable (e.g., rels := ParseKGRelationChunks(chunks)) and use require/if to guard that rels has elements then assert rels[0].Weight == 3; reference the ParseKGRelationChunks call and the Weight check in kg_search_test.go when making the change.internal/common/metadata_utils_test.go (1)
518-529: ⚡ Quick winAdd a mixed date/non-date
≠regression test.The new branch on Line 277 only returns true for
≠when the filter value is a date and the metadata value is not. The suite still exercises the mixed-type path with>only, so this changed behavior can regress without a failing test.Suggested test
+func TestMetaFilter_DateVsNonDate_NotEquals(t *testing.T) { + metas := MetaData{ + "date_field": {"xyz": {"doc1"}, "2024-01-01": {"doc2"}}, + } + input := &MetaFilterInput{ + Conditions: []MetaCondition{{Operator: "≠", Key: "date_field", Value: "2024-01-01"}}, + } + result := MetaFilter(metas, input) + if len(result) != 1 || result[0] != "doc1" { + t.Errorf("expected only non-date mismatch [doc1], got %v", result) + } +}🤖 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/common/metadata_utils_test.go` around lines 518 - 529, Add a regression test to cover the mixed date/non-date path for the "≠" operator: create a new test (e.g., TestMetaFilter_NotEquals_MixedDateNonDate) that calls MetaFilter with a MetaData entry where the stored value is a non-date string and the MetaFilterInput uses a date-formatted Value (and include the reverse case too: stored value date, filter value non-date) using MetaCondition {Operator: "≠", Key: "author", Value: "..."} to assert the expected document is returned; this ensures MetaFilter's ≠ handling for mixed-type (date vs non-date) values is exercised alongside existing TestMetaFilter_NotEquals and guards the new branch added around line ~277.
🤖 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/common/metadata_utils.go`:
- Around line 205-208: filterSet currently expects value to be []interface{} and
returns nil for strings, causing inconsistent behavior between
service.convertToMetaCondition and common.ParseAndConvert; fix by centralizing
coercion so the MetaCondition shape is consistent: update ParseAndConvert to
detect "in"/"not in" operators and coerce cond["value"] (including
comma-separated strings like "A,B") into []interface{} (or alternatively add
coercion inside filterSet to accept string and split into []interface{}),
ensuring both ParseAndConvert and service.convertToMetaCondition produce the
same []interface{} shape used by filterSet and MetaCondition handling.
---
Nitpick comments:
In `@internal/common/metadata_utils_test.go`:
- Around line 518-529: Add a regression test to cover the mixed date/non-date
path for the "≠" operator: create a new test (e.g.,
TestMetaFilter_NotEquals_MixedDateNonDate) that calls MetaFilter with a MetaData
entry where the stored value is a non-date string and the MetaFilterInput uses a
date-formatted Value (and include the reverse case too: stored value date,
filter value non-date) using MetaCondition {Operator: "≠", Key: "author", Value:
"..."} to assert the expected document is returned; this ensures MetaFilter's ≠
handling for mixed-type (date vs non-date) values is exercised alongside
existing TestMetaFilter_NotEquals and guards the new branch added around line
~277.
In `@internal/service/kg_search_test.go`:
- Line 196: The test indexing ParseKGEntityChunks(chunks)[0] is fragile and can
panic if ParseKGEntityChunks returns an empty slice; change the test to first
assign the result to a variable (e.g., entities := ParseKGEntityChunks(chunks)),
assert or require that len(entities) > 0, and only then check
entities[0].Similarity == 0.75 (use the existing testing/assert helper in
kg_search_test.go to fail the test cleanly if empty).
- Line 221: The test is indexing ParseKGRelationChunks(chunks)[0] without
checking the slice length, risking an index out of bounds; update the test to
first assert the returned slice has the expected length (e.g.,
len(ParseKGRelationChunks(chunks)) > 0 or compare to an exact expected length)
before accessing element 0, or capture the result into a variable (e.g., rels :=
ParseKGRelationChunks(chunks)) and use require/if to guard that rels has
elements then assert rels[0].Weight == 3; reference the ParseKGRelationChunks
call and the Weight check in kg_search_test.go when making the change.
In `@internal/service/kg_search.go`:
- Line 87: Document why the fusion weights favor text retrieval by adding a
brief inline comment next to the FusionParams declaration that sets
map[string]interface{}{"weights": "0.05,0.95"} (in the code that builds the
search parameters, i.e., the FusionParams field). Explain that 0.05/0.95 was
chosen to prioritize exact/name-based text matches over dense embeddings for KG
entity matching (or note any alternative rationale), and include a note about
when/if these should be adjusted.
- Around line 306-362: Add input validation to the public search functions
(SearchKGEntities, SearchKGEntitiesByTypes, SearchKGRelations,
SearchKGCommunityReports, SearchKGTypeSamples) to guard against nil docEngine,
empty kbIDs, and invalid topN (<=0); return a descriptive error immediately if
docEngine == nil, if len(kbIDs)==0 where a KB selection is required, or if topN
<= 0 (or normalize topN to a sensible default) so downstream calls to
docEngine.Search and build*Request functions cannot panic or send bad queries.
Use the function names above to locate each entry point and apply the same
checks consistently at the start of each function.
- Line 75: The hardcoded similarity value (ExtraOptions:
map[string]interface{}{"similarity": 0.3}) should be made configurable:
introduce a named parameter or field (e.g., SimilarityThreshold float64) on the
KG search config/constructor (such as the searcher struct or New... function
used in kg_search.go), default it to 0.3 when unset, read an environment/config
value or accept it from callers, and replace the hardcoded literal with that
variable when building ExtraOptions so callers can tune the threshold without
editing the code.
- Around line 274-276: The merge loop appends entities from typeMap into result
without deduplication, causing duplicate entity strings (e.g., "Alice") when the
same type appears in multiple chunks; modify the merging code that iterates over
typeMap (the for typ, entities := range typeMap loop) to deduplicate before
appending by tracking seen entities per type (e.g., a
map[string]map[string]struct{} or a map[string]set for each typ), only adding
entities not already present in result[typ], and then convert back to the slice
for result[typ]; ensure you update or reuse result[typ]’s existing entries when
checking the seen set so no duplicates are introduced.
🪄 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: 8dfa65c4-c5fd-4aa0-9a3c-7456ae72b695
📒 Files selected for processing (6)
internal/common/metadata_utils.gointernal/common/metadata_utils_test.gointernal/service/kg_search.gointernal/service/kg_search_test.gointernal/service/metadata_filter.gointernal/service/metadata_filter_test.go
| func filterSet(v2docs MetaValueDocs, operator string, value interface{}) []string { | ||
| list, ok := value.([]interface{}) | ||
| if !ok { | ||
| return nil |
There was a problem hiding this comment.
in/not in now depend on a value shape that ParseAndConvert still doesn't produce.
Line 206 fails closed unless value is []interface{}, but ParseAndConvert still passes raw cond["value"] through unchanged. That makes the same payload behave differently depending on the entry point: service.convertToMetaCondition will split "A,B" correctly, while common.ParseAndConvert will send a string here and silently match nothing. Please centralize the list coercion so both paths build the same MetaCondition shape.
🤖 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/common/metadata_utils.go` around lines 205 - 208, filterSet
currently expects value to be []interface{} and returns nil for strings, causing
inconsistent behavior between service.convertToMetaCondition and
common.ParseAndConvert; fix by centralizing coercion so the MetaCondition shape
is consistent: update ParseAndConvert to detect "in"/"not in" operators and
coerce cond["value"] (including comma-separated strings like "A,B") into
[]interface{} (or alternatively add coercion inside filterSet to accept string
and split into []interface{}), ensuring both ParseAndConvert and
service.convertToMetaCondition produce the same []interface{} shape used by
filterSet and MetaCondition handling.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15689 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Summary
Knowledge Graph search functions for entity, relation, community report, and type-samples retrieval. Uses DocEngine.SelectFields (PR #15684) for KG-specific fields.
Functions
SearchKGEntitiesSearchKGEntitiesByTypesentity_type_kwdSearchKGRelationsSearchKGCommunityReportsSearchKGTypeSamplesInternal helpers
buildHybridExprbuildKGDenseExprEmbed()call for vector searchParse*Testing
35 tests (pure function + mock integration)
Co-Authored-By: Claude Opus 4.8 [email protected]