chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

@@ -0,0 +1,78 @@
package elasticsearch
import (
"maps"
"slices"
"academy/internal/types"
)
// VectorEmbedding defines the Elasticsearch document structure for vector embeddings
type VectorEmbedding struct {
Content string `json:"content" gorm:"column:content;not null"` // Text content of the chunk
SourceID string `json:"source_id" gorm:"column:source_id;not null"` // ID of the source document
SourceType int `json:"source_type" gorm:"column:source_type;not null"` // Type of the source document
ChunkID string `json:"chunk_id" gorm:"column:chunk_id"` // Unique ID of the text chunk
KnowledgeID string `json:"knowledge_id" gorm:"column:knowledge_id"` // ID of the knowledge item
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"column:knowledge_base_id"` // ID of the knowledge base
TagID string `json:"tag_id" gorm:"column:tag_id"` // Tag ID for categorization
Embedding []float32 `json:"embedding" gorm:"column:embedding;not null"` // Vector embedding of the content
IsEnabled bool `json:"is_enabled"` // Whether the chunk is enabled
IsRecommended bool `json:"is_recommended"` // Whether the chunk is recommended
}
// VectorEmbeddingWithScore extends VectorEmbedding with similarity score
type VectorEmbeddingWithScore struct {
VectorEmbedding
Score float64 // Similarity score from vector search
}
// ToDBVectorEmbedding converts IndexInfo to Elasticsearch document format
func ToDBVectorEmbedding(embedding *types.IndexInfo, additionalParams map[string]interface{}) *VectorEmbedding {
vector := &VectorEmbedding{
Content: embedding.Content,
SourceID: embedding.SourceID,
SourceType: int(embedding.SourceType),
ChunkID: embedding.ChunkID,
KnowledgeID: embedding.KnowledgeID,
KnowledgeBaseID: embedding.KnowledgeBaseID,
TagID: embedding.TagID,
IsEnabled: embedding.IsEnabled,
IsRecommended: embedding.IsRecommended,
}
// Add embedding data if available in additionalParams
if additionalParams != nil && slices.Contains(slices.Collect(maps.Keys(additionalParams)), "embedding") {
if embeddingMap, ok := additionalParams["embedding"].(map[string][]float32); ok {
vector.Embedding = embeddingMap[embedding.SourceID]
}
}
// Get is_enabled from additionalParams if available
if additionalParams != nil {
if chunkEnabledMap, ok := additionalParams["chunk_enabled"].(map[string]bool); ok {
if enabled, exists := chunkEnabledMap[embedding.ChunkID]; exists {
vector.IsEnabled = enabled
}
}
}
return vector
}
// FromDBVectorEmbeddingWithScore converts Elasticsearch document to IndexWithScore domain model
func FromDBVectorEmbeddingWithScore(id string,
embedding *VectorEmbeddingWithScore,
matchType types.MatchType,
) *types.IndexWithScore {
return &types.IndexWithScore{
ID: id,
SourceID: embedding.SourceID,
SourceType: types.SourceType(embedding.SourceType),
ChunkID: embedding.ChunkID,
KnowledgeID: embedding.KnowledgeID,
KnowledgeBaseID: embedding.KnowledgeBaseID,
TagID: embedding.TagID,
Content: embedding.Content,
Score: embedding.Score,
MatchType: matchType,
IsEnabled: embedding.IsEnabled,
}
}
@@ -0,0 +1,150 @@
package v7
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
typesLocal "academy/internal/types"
"academy/internal/types/interfaces"
"github.com/elastic/go-elasticsearch/v7"
)
// bulkReasonSentinel stands for document content that a per-item error.reason
// can carry; the error returned to the caller must never include it.
const bulkReasonSentinel = "LEAK-SENTINEL-DOC-BODY"
// fakeBulkServer answers every request the v7 repository makes while BatchSave
// runs, and returns body for the _bulk call.
type fakeBulkServer struct {
body string
calls int
}
func (f *fakeBulkServer) handler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case strings.HasSuffix(r.URL.Path, "/_bulk"):
f.calls++
_, _ = io.WriteString(w, f.body)
case strings.HasSuffix(r.URL.Path, "/_mapping"):
_, _ = io.WriteString(w,
`{"xwrag_default":{"mappings":{"properties":{"chunk_id":{"type":"keyword"}}}}}`)
case r.Method == http.MethodHead:
w.WriteHeader(http.StatusNotFound)
default:
_, _ = io.WriteString(w,
`{"acknowledged":true,"shards_acknowledged":true,"index":"xwrag_default"}`)
}
}
}
// newBulkTestRepository builds the repository through its public constructor
// against a fake Elasticsearch that answers _bulk with body.
func newBulkTestRepository(t *testing.T, body string) (interfaces.RetrieveEngineRepository, *fakeBulkServer) {
t.Helper()
fake := &fakeBulkServer{body: body}
server := httptest.NewServer(fake.handler())
t.Cleanup(server.Close)
client, err := elasticsearch.NewClient(
elasticsearch.Config{Addresses: []string{server.URL}, DisableRetry: true},
)
require.NoError(t, err)
return NewElasticsearchEngineRepository(client, nil, nil), fake
}
func bulkTestIndexInfos() []*typesLocal.IndexInfo {
return []*typesLocal.IndexInfo{
{
Content: "alpha", SourceID: "src-1", SourceType: typesLocal.ChunkSourceType,
ChunkID: "chunk-1", KnowledgeID: "k-1", KnowledgeBaseID: "kb-1", IsEnabled: true,
},
{
Content: "beta", SourceID: "src-2", SourceType: typesLocal.ChunkSourceType,
ChunkID: "chunk-2", KnowledgeID: "k-1", KnowledgeBaseID: "kb-1", IsEnabled: true,
},
}
}
func bulkTestParams() map[string]any {
return map[string]any{
"embedding": map[string][]float32{"src-1": {0.1, 0.2}, "src-2": {0.3, 0.4}},
}
}
// TestBatchSaveReportsPerItemBulkErrors is a regression test for #3832:
// Elasticsearch answers an accepted _bulk request with HTTP 200, so a document
// rejected for a mapping mismatch, a read-only index or an item-level
// rejection is visible only in the response body. BatchSave must surface those
// per-item failures instead of logging a warning and reporting success.
func TestBatchSaveReportsPerItemBulkErrors(t *testing.T) {
cases := []struct {
name string
body string
wantContains []string
}{
{
name: "all documents rejected",
body: `{"took":1,"errors":true,"items":[` +
`{"index":{"_id":"chunk-1","status":400,` +
`"error":{"type":"mapper_parsing_exception","reason":"` + bulkReasonSentinel + `"}}},` +
`{"index":{"_id":"chunk-2","status":429,` +
`"error":{"type":"es_rejected_execution_exception","reason":"` + bulkReasonSentinel + `"}}}]}`,
wantContains: []string{
"2/2 documents failed",
"chunk-1", "mapper_parsing_exception",
"chunk-2", "es_rejected_execution_exception",
},
},
{
name: "partial failure",
body: `{"took":1,"errors":true,"items":[` +
`{"index":{"_id":"chunk-1","status":201,"result":"created"}},` +
`{"index":{"_id":"chunk-2","status":400,` +
`"error":{"type":"cluster_block_exception","reason":"` + bulkReasonSentinel + `"}}}]}`,
wantContains: []string{"1/2 documents failed", "chunk-2", "cluster_block_exception"},
},
{
name: "malformed response body",
body: `{"took":1`,
wantContains: []string{"failed to parse bulk response"},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
repo, fake := newBulkTestRepository(t, tc.body)
err := repo.BatchSave(context.Background(), bulkTestIndexInfos(), bulkTestParams())
require.Positive(t, fake.calls, "the _bulk endpoint was never called")
require.Error(t, err)
for _, want := range tc.wantContains {
assert.Contains(t, err.Error(), want)
}
assert.NotContains(t, err.Error(), bulkReasonSentinel,
"the returned error must not carry error.reason")
})
}
t.Run("all documents accepted", func(t *testing.T) {
repo, fake := newBulkTestRepository(t, `{"took":1,"errors":false,"items":[`+
`{"index":{"_id":"chunk-1","status":201,"result":"created"}},`+
`{"index":{"_id":"chunk-2","status":201,"result":"created"}}]}`)
err := repo.BatchSave(context.Background(), bulkTestIndexInfos(), bulkTestParams())
require.Positive(t, fake.calls, "the _bulk endpoint was never called")
require.NoError(t, err)
})
}
@@ -0,0 +1,145 @@
package v7
import (
"bufio"
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/elastic/go-elasticsearch/v7"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// copySourceHits covers every source_id shape CopyIndices remaps: a regular
// chunk row, a generated-question row sharing that chunk, a row with an
// unrelated source_id (remapped to a fresh uuid), and a legacy row written
// before is_enabled existed.
const copySourceHits = `[
{"_index":"vectors","_id":"d1","_score":1,"_source":{"content":"chunk","source_id":"c1","source_type":0,
"chunk_id":"c1","knowledge_id":"k1","knowledge_base_id":"kb-src","embedding":[0.1,0.2],"is_enabled":true}},
{"_index":"vectors","_id":"d2","_score":1,"_source":{"content":"question","source_id":"c1-q1","source_type":1,
"chunk_id":"c1","knowledge_id":"k1","knowledge_base_id":"kb-src","embedding":[0.3,0.4],"is_enabled":true}},
{"_index":"vectors","_id":"d3","_score":1,"_source":{"content":"summary","source_id":"img-9","source_type":2,
"chunk_id":"c2","knowledge_id":"k1","knowledge_base_id":"kb-src","embedding":[0.5,0.6],"is_enabled":false}},
{"_index":"vectors","_id":"d4","_score":1,"_source":{"content":"legacy","source_id":"c3","source_type":0,
"chunk_id":"c3","knowledge_id":"k1","knowledge_base_id":"kb-src","embedding":[0.7,0.8]}}
]`
type copiedDoc struct {
Content string `json:"content"`
SourceID string `json:"source_id"`
SourceType int `json:"source_type"`
ChunkID string `json:"chunk_id"`
KnowledgeID string `json:"knowledge_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
Embedding []float32 `json:"embedding"`
IsEnabled *bool `json:"is_enabled"`
}
// fakeCopyServer serves one page of copySourceHits and records the search
// query and every document sent through _bulk.
type fakeCopyServer struct {
mu sync.Mutex
searchQuery string
docs []copiedDoc
}
func (f *fakeCopyServer) handler(t *testing.T) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Elastic-Product", "Elasticsearch")
body, _ := io.ReadAll(r.Body)
f.mu.Lock()
defer f.mu.Unlock()
switch r.URL.Path {
case "/":
_, _ = w.Write([]byte(`{"version":{"number":"7.17.0","build_flavor":"default"},` +
`"tagline":"You Know, for Search"}`))
case "/vectors/_search":
f.searchQuery = string(body)
_, _ = w.Write([]byte(`{"took":1,"timed_out":false,` +
`"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},` +
`"hits":{"total":{"value":4,"relation":"eq"},"hits":` + copySourceHits + `}}`))
case "/vectors/_bulk":
sc := bufio.NewScanner(bytes.NewReader(body))
sc.Buffer(make([]byte, 0, 1<<20), 1<<20)
for sc.Scan() {
line := sc.Bytes()
var probe map[string]json.RawMessage
require.NoError(t, json.Unmarshal(line, &probe))
if _, ok := probe["content"]; !ok {
continue // action line
}
var doc copiedDoc
require.NoError(t, json.Unmarshal(line, &doc))
f.docs = append(f.docs, doc)
}
_, _ = w.Write([]byte(`{"took":1,"errors":false,"items":[]}`))
default:
t.Errorf("unexpected path: %s", r.URL.Path)
}
}
}
func TestCopyIndicesKeepsVectorsAndEnabledState(t *testing.T) {
fake := &fakeCopyServer{}
server := httptest.NewServer(fake.handler(t))
defer server.Close()
client, err := elasticsearch.NewClient(
elasticsearch.Config{Addresses: []string{server.URL}, DisableRetry: true},
)
require.NoError(t, err)
repo := &elasticsearchRepository{client: client, index: "vectors"}
err = repo.CopyIndices(context.Background(), "kb-src",
map[string]string{"k1": "tk1"},
map[string]string{"c1": "t1", "c2": "t2", "c3": "t3"},
"kb-dst", 2, "manual")
require.NoError(t, err)
assert.NotContains(t, fake.searchQuery, "is_enabled",
"the copy scan must include disabled source rows so they stay disabled, not vanish")
require.Len(t, fake.docs, 4)
byContent := make(map[string]copiedDoc, len(fake.docs))
for _, d := range fake.docs {
byContent[d.Content] = d
assert.Equal(t, "tk1", d.KnowledgeID)
assert.Equal(t, "kb-dst", d.KnowledgeBaseID)
require.NotNil(t, d.IsEnabled, "is_enabled must be written for %q", d.Content)
}
chunk := byContent["chunk"]
assert.Equal(t, "t1", chunk.ChunkID)
assert.Equal(t, "t1", chunk.SourceID)
assert.Equal(t, 0, chunk.SourceType)
assert.Equal(t, []float32{0.1, 0.2}, chunk.Embedding)
assert.True(t, *chunk.IsEnabled)
question := byContent["question"]
assert.Equal(t, "t1", question.ChunkID)
assert.Equal(t, "t1-q1", question.SourceID)
assert.Equal(t, 1, question.SourceType)
assert.Equal(t, []float32{0.3, 0.4}, question.Embedding)
assert.True(t, *question.IsEnabled)
summary := byContent["summary"]
assert.Equal(t, "t2", summary.ChunkID)
assert.NotEqual(t, "img-9", summary.SourceID)
assert.False(t, strings.HasPrefix(summary.SourceID, "t2"), "unrelated source ids get a fresh uuid")
assert.Equal(t, 2, summary.SourceType)
assert.Equal(t, []float32{0.5, 0.6}, summary.Embedding)
assert.False(t, *summary.IsEnabled)
legacy := byContent["legacy"]
assert.Equal(t, "t3", legacy.SourceID)
assert.Equal(t, []float32{0.7, 0.8}, legacy.Embedding)
assert.True(t, *legacy.IsEnabled, "a source row without is_enabled is enabled for retrieval")
}
@@ -0,0 +1,59 @@
package v7
import (
"bytes"
"context"
"encoding/json"
"fmt"
)
func (e *elasticsearchRepository) MoveKnowledgeIndices(
ctx context.Context,
sourceKB, targetKB, knowledgeID string,
_ []string,
_ int,
_ string,
) error {
body, err := json.Marshal(map[string]any{
"query": map[string]any{"bool": map[string]any{"filter": []any{
map[string]any{"term": map[string]any{e.idField("knowledge_base_id"): sourceKB}},
map[string]any{"term": map[string]any{e.idField("knowledge_id"): knowledgeID}},
}}},
"script": map[string]any{
"lang": "painless",
"source": "ctx._source.knowledge_base_id = params.target; ctx._source.tag_id = ''",
"params": map[string]any{"target": targetKB},
},
})
if err != nil {
return err
}
resp, err := e.client.UpdateByQuery(
[]string{e.index},
e.client.UpdateByQuery.WithContext(ctx),
e.client.UpdateByQuery.WithBody(bytes.NewReader(body)),
e.client.UpdateByQuery.WithRefresh(true),
)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
if resp.IsError() {
return fmt.Errorf("move indices: %s", resp.String())
}
var result struct {
Total *int64 `json:"total"`
Updated *int64 `json:"updated"`
TimedOut bool `json:"timed_out"`
Conflicts int `json:"version_conflicts"`
Failures []json.RawMessage `json:"failures"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return err
}
if result.Total == nil || result.Updated == nil || *result.Total < 0 || *result.Total != *result.Updated ||
result.TimedOut || result.Conflicts != 0 || len(result.Failures) != 0 {
return fmt.Errorf("move indices was incomplete")
}
return nil
}
@@ -0,0 +1,59 @@
package v7
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/elastic/go-elasticsearch/v7"
"github.com/stretchr/testify/require"
)
func TestMoveIndicesRequiresCompleteCounts(t *testing.T) {
for _, tt := range []struct {
name, body string
fails bool
}{
{"complete", `{"total":100,"updated":100}`, false},
{"empty retry", `{"total":0,"updated":0}`, false},
{"partial", `{"total":100,"updated":40}`, true},
{"missing total", `{"updated":40}`, true},
{"missing updated", `{"total":40}`, true},
{"missing counts", `{}`, true},
{"negative", `{"total":-1,"updated":-1}`, true},
{"conflict", `{"total":1,"updated":1,"version_conflicts":1}`, true},
{"timeout", `{"total":1,"updated":1,"timed_out":true}`, true},
} {
t.Run(tt.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Elastic-Product", "Elasticsearch")
if r.URL.Path == "/" {
_, _ = w.Write(
[]byte(
`{"version":{"number":"7.17.0","build_flavor":"default"},"tagline":"You Know, for Search"}`,
),
)
return
}
if r.URL.Path != "/vectors/_update_by_query" {
t.Errorf("unexpected path: %s", r.URL.Path)
}
_, _ = w.Write([]byte(tt.body))
}))
defer server.Close()
client, err := elasticsearch.NewClient(
elasticsearch.Config{Addresses: []string{server.URL}, DisableRetry: true},
)
require.NoError(t, err)
repo := &elasticsearchRepository{client: client, index: "vectors"}
err = repo.MoveKnowledgeIndices(context.Background(), "source", "target", "doc", nil, 3, "file")
if tt.fails {
require.Error(t, err)
} else {
require.NoError(t, err)
}
})
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,52 @@
package v7
import (
"context"
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
typesLocal "academy/internal/types"
)
// Regression test for #3156: the script_score source must floor the cosine
// similarity at 0. An unclamped negative cosine makes Lucene reject the whole
// search request ("script_score script returned an invalid score ... Must be a
// non-negative score!"), turning one dissimilar document into a full vector
// retrieval outage (all shards failed).
func TestVectorScoreScriptSourceClampsNegativeCosine(t *testing.T) {
require.Equal(t,
"Math.max(cosineSimilarity(params.query_vector,'embedding'), 0.0)",
vectorScoreScriptSource)
}
// The marshaled query body must carry the clamped script source end to end.
func TestBuildVectorSearchQueryClampsScriptScore(t *testing.T) {
e := &elasticsearchRepository{}
params := typesLocal.RetrieveParams{
Embedding: []float32{-1, 0},
Threshold: 0.15,
TopK: 5,
KnowledgeBaseIDs: []string{"kb-1"},
}
query, err := e.buildVectorSearchQuery(context.Background(), params)
require.NoError(t, err)
var body struct {
Query struct {
ScriptScore struct {
Script struct {
Source string `json:"source"`
} `json:"script"`
MinScore float64 `json:"min_score"`
} `json:"script_score"`
} `json:"query"`
}
require.NoError(t, json.Unmarshal([]byte(query), &body))
require.Equal(t,
"Math.max(cosineSimilarity(params.query_vector,'embedding'), 0.0)",
body.Query.ScriptScore.Script.Source)
require.InDelta(t, 0.15, body.Query.ScriptScore.MinScore, 1e-6)
}
@@ -0,0 +1,146 @@
package v8
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
typesLocal "academy/internal/types"
"academy/internal/types/interfaces"
"github.com/elastic/go-elasticsearch/v8"
)
// bulkReasonSentinel stands for document content that a per-item error.reason
// can carry; the error returned to the caller must never include it.
const bulkReasonSentinel = "LEAK-SENTINEL-DOC-BODY"
// fakeBulkServer answers every request the v8 repository makes while BatchSave
// runs, and returns body for the _bulk call.
type fakeBulkServer struct {
body string
calls int
}
func (f *fakeBulkServer) handler() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Elastic-Product", "Elasticsearch")
switch {
case strings.HasSuffix(r.URL.Path, "/_bulk"):
f.calls++
_, _ = io.WriteString(w, f.body)
case strings.HasSuffix(r.URL.Path, "/_mapping"):
_, _ = io.WriteString(w,
`{"xwrag_default":{"mappings":{"properties":{"chunk_id":{"type":"keyword"}}}}}`)
case r.Method == http.MethodHead:
w.WriteHeader(http.StatusNotFound)
default:
_, _ = io.WriteString(w,
`{"acknowledged":true,"shards_acknowledged":true,"index":"xwrag_default"}`)
}
}
}
// newBulkTestRepository builds the repository through its public constructor
// against a fake Elasticsearch that answers _bulk with body.
func newBulkTestRepository(t *testing.T, body string) (interfaces.RetrieveEngineRepository, *fakeBulkServer) {
t.Helper()
fake := &fakeBulkServer{body: body}
server := httptest.NewServer(fake.handler())
t.Cleanup(server.Close)
client, err := elasticsearch.NewTypedClient(
elasticsearch.Config{Addresses: []string{server.URL}, DisableRetry: true},
)
require.NoError(t, err)
return NewElasticsearchEngineRepository(client, nil, nil), fake
}
func bulkTestIndexInfos() []*typesLocal.IndexInfo {
return []*typesLocal.IndexInfo{
{
Content: "alpha", SourceID: "src-1", SourceType: typesLocal.ChunkSourceType,
ChunkID: "chunk-1", KnowledgeID: "k-1", KnowledgeBaseID: "kb-1", IsEnabled: true,
},
{
Content: "beta", SourceID: "src-2", SourceType: typesLocal.ChunkSourceType,
ChunkID: "chunk-2", KnowledgeID: "k-1", KnowledgeBaseID: "kb-1", IsEnabled: true,
},
}
}
func bulkTestParams() map[string]any {
return map[string]any{
"embedding": map[string][]float32{"src-1": {0.1, 0.2}, "src-2": {0.3, 0.4}},
}
}
// TestBatchSaveReportsPerItemBulkErrors is a regression test for #3832:
// Elasticsearch answers an accepted _bulk request with HTTP 200, so a document
// rejected for a mapping mismatch, a read-only index or an item-level
// rejection is visible only in the response body. BatchSave must surface those
// per-item failures to the caller.
func TestBatchSaveReportsPerItemBulkErrors(t *testing.T) {
cases := []struct {
name string
body string
wantContains []string
}{
{
name: "all documents rejected",
body: `{"took":1,"errors":true,"items":[` +
`{"create":{"_id":"chunk-1","status":400,` +
`"error":{"type":"mapper_parsing_exception","reason":"` + bulkReasonSentinel + `"}}},` +
`{"create":{"_id":"chunk-2","status":429,` +
`"error":{"type":"es_rejected_execution_exception","reason":"` + bulkReasonSentinel + `"}}}]}`,
wantContains: []string{
"2/2 documents failed",
"chunk-1", "mapper_parsing_exception",
"chunk-2", "es_rejected_execution_exception",
},
},
{
name: "partial failure",
body: `{"took":1,"errors":true,"items":[` +
`{"create":{"_id":"chunk-1","status":201,"result":"created"}},` +
`{"create":{"_id":"chunk-2","status":400,` +
`"error":{"type":"cluster_block_exception","reason":"` + bulkReasonSentinel + `"}}}]}`,
wantContains: []string{"1/2 documents failed", "chunk-2", "cluster_block_exception"},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
repo, fake := newBulkTestRepository(t, tc.body)
err := repo.BatchSave(context.Background(), bulkTestIndexInfos(), bulkTestParams())
require.Positive(t, fake.calls, "the _bulk endpoint was never called")
require.Error(t, err)
for _, want := range tc.wantContains {
assert.Contains(t, err.Error(), want)
}
assert.NotContains(t, err.Error(), bulkReasonSentinel,
"the returned error must not carry error.reason")
})
}
t.Run("all documents accepted", func(t *testing.T) {
repo, fake := newBulkTestRepository(t, `{"took":1,"errors":false,"items":[`+
`{"create":{"_id":"chunk-1","status":201,"result":"created"}},`+
`{"create":{"_id":"chunk-2","status":201,"result":"created"}}]}`)
err := repo.BatchSave(context.Background(), bulkTestIndexInfos(), bulkTestParams())
require.Positive(t, fake.calls, "the _bulk endpoint was never called")
require.NoError(t, err)
})
}
@@ -0,0 +1,142 @@
package v8
import (
"bufio"
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/elastic/go-elasticsearch/v8"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// copySourceHits covers every source_id shape CopyIndices remaps: a regular
// chunk row, a generated-question row sharing that chunk, a row with an
// unrelated source_id (remapped to a fresh uuid), and a legacy row written
// before is_enabled existed.
const copySourceHits = `[
{"_index":"vectors","_id":"d1","_score":1,"_source":{"content":"chunk","source_id":"c1","source_type":0,
"chunk_id":"c1","knowledge_id":"k1","knowledge_base_id":"kb-src","embedding":[0.1,0.2],"is_enabled":true}},
{"_index":"vectors","_id":"d2","_score":1,"_source":{"content":"question","source_id":"c1-q1","source_type":1,
"chunk_id":"c1","knowledge_id":"k1","knowledge_base_id":"kb-src","embedding":[0.3,0.4],"is_enabled":true}},
{"_index":"vectors","_id":"d3","_score":1,"_source":{"content":"summary","source_id":"img-9","source_type":2,
"chunk_id":"c2","knowledge_id":"k1","knowledge_base_id":"kb-src","embedding":[0.5,0.6],"is_enabled":false}},
{"_index":"vectors","_id":"d4","_score":1,"_source":{"content":"legacy","source_id":"c3","source_type":0,
"chunk_id":"c3","knowledge_id":"k1","knowledge_base_id":"kb-src","embedding":[0.7,0.8]}}
]`
type copiedDoc struct {
Content string `json:"content"`
SourceID string `json:"source_id"`
SourceType int `json:"source_type"`
ChunkID string `json:"chunk_id"`
KnowledgeID string `json:"knowledge_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
Embedding []float32 `json:"embedding"`
IsEnabled *bool `json:"is_enabled"`
}
// fakeCopyServer serves one page of copySourceHits and records the search
// query and every document sent through _bulk.
type fakeCopyServer struct {
mu sync.Mutex
searchQuery string
docs []copiedDoc
}
func (f *fakeCopyServer) handler(t *testing.T) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Elastic-Product", "Elasticsearch")
body, _ := io.ReadAll(r.Body)
f.mu.Lock()
defer f.mu.Unlock()
switch r.URL.Path {
case "/vectors/_search":
f.searchQuery = string(body)
_, _ = w.Write([]byte(`{"took":1,"timed_out":false,` +
`"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},` +
`"hits":{"total":{"value":4,"relation":"eq"},"hits":` + copySourceHits + `}}`))
case "/vectors/_bulk":
sc := bufio.NewScanner(bytes.NewReader(body))
sc.Buffer(make([]byte, 0, 1<<20), 1<<20)
for sc.Scan() {
line := sc.Bytes()
var probe map[string]json.RawMessage
require.NoError(t, json.Unmarshal(line, &probe))
if _, ok := probe["content"]; !ok {
continue // action line
}
var doc copiedDoc
require.NoError(t, json.Unmarshal(line, &doc))
f.docs = append(f.docs, doc)
}
_, _ = w.Write([]byte(`{"took":1,"errors":false,"items":[]}`))
default:
t.Errorf("unexpected path: %s", r.URL.Path)
}
}
}
func TestCopyIndicesKeepsVectorsAndEnabledState(t *testing.T) {
fake := &fakeCopyServer{}
server := httptest.NewServer(fake.handler(t))
defer server.Close()
client, err := elasticsearch.NewTypedClient(
elasticsearch.Config{Addresses: []string{server.URL}, DisableRetry: true},
)
require.NoError(t, err)
repo := &elasticsearchRepository{client: client, index: "vectors"}
err = repo.CopyIndices(context.Background(), "kb-src",
map[string]string{"k1": "tk1"},
map[string]string{"c1": "t1", "c2": "t2", "c3": "t3"},
"kb-dst", 2, "manual")
require.NoError(t, err)
assert.NotContains(t, fake.searchQuery, "is_enabled",
"the copy scan must include disabled source rows so they stay disabled, not vanish")
require.Len(t, fake.docs, 4)
byContent := make(map[string]copiedDoc, len(fake.docs))
for _, d := range fake.docs {
byContent[d.Content] = d
assert.Equal(t, "tk1", d.KnowledgeID)
assert.Equal(t, "kb-dst", d.KnowledgeBaseID)
require.NotNil(t, d.IsEnabled, "is_enabled must be written for %q", d.Content)
}
chunk := byContent["chunk"]
assert.Equal(t, "t1", chunk.ChunkID)
assert.Equal(t, "t1", chunk.SourceID)
assert.Equal(t, 0, chunk.SourceType)
assert.Equal(t, []float32{0.1, 0.2}, chunk.Embedding)
assert.True(t, *chunk.IsEnabled)
question := byContent["question"]
assert.Equal(t, "t1", question.ChunkID)
assert.Equal(t, "t1-q1", question.SourceID)
assert.Equal(t, 1, question.SourceType)
assert.Equal(t, []float32{0.3, 0.4}, question.Embedding)
assert.True(t, *question.IsEnabled)
summary := byContent["summary"]
assert.Equal(t, "t2", summary.ChunkID)
assert.NotEqual(t, "img-9", summary.SourceID)
assert.False(t, strings.HasPrefix(summary.SourceID, "t2"), "unrelated source ids get a fresh uuid")
assert.Equal(t, 2, summary.SourceType)
assert.Equal(t, []float32{0.5, 0.6}, summary.Embedding)
assert.False(t, *summary.IsEnabled)
legacy := byContent["legacy"]
assert.Equal(t, "t3", legacy.SourceID)
assert.Equal(t, []float32{0.7, 0.8}, legacy.Embedding)
assert.True(t, *legacy.IsEnabled, "a source row without is_enabled is enabled for retrieval")
}
@@ -0,0 +1,48 @@
// Package v8 implements retrieval against its configured vector backend.
package v8
import (
"context"
"encoding/json"
"fmt"
"github.com/elastic/go-elasticsearch/v8/typedapi/types"
)
func (e *elasticsearchRepository) MoveKnowledgeIndices(
ctx context.Context,
sourceKB, targetKB, knowledgeID string,
_ []string,
_ int,
_ string,
) error {
query := &types.Query{Bool: &types.BoolQuery{Filter: []types.Query{
{
Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{e.idField("knowledge_base_id"): []string{sourceKB}},
},
},
{
Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{e.idField("knowledge_id"): []string{knowledgeID}},
},
},
}}}
source := "ctx._source.knowledge_base_id = params.target; ctx._source.tag_id = ''"
target, err := json.Marshal(targetKB)
if err != nil {
return err
}
script := &types.Script{Source: &source, Params: map[string]json.RawMessage{"target": target}}
result, err := e.client.UpdateByQuery(e.index).Query(query).Script(script).Refresh(true).Do(ctx)
if err != nil {
return err
}
if result == nil || result.Total == nil || result.Updated == nil ||
*result.Total < 0 || *result.Total != *result.Updated || (result.TimedOut != nil && *result.TimedOut) ||
(result.VersionConflicts != nil && *result.VersionConflicts != 0) ||
len(result.Failures) != 0 {
return fmt.Errorf("move indices was incomplete")
}
return nil
}
@@ -0,0 +1,59 @@
package v8
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"github.com/elastic/go-elasticsearch/v8"
"github.com/stretchr/testify/require"
)
func TestMoveIndicesRequiresCompleteCounts(t *testing.T) {
for _, tt := range []struct {
name, body string
fails bool
}{
{"complete", `{"total":100,"updated":100}`, false},
{"empty retry", `{"total":0,"updated":0}`, false},
{"partial", `{"total":100,"updated":40}`, true},
{"missing total", `{"updated":40}`, true},
{"missing updated", `{"total":40}`, true},
{"missing counts", `{}`, true},
{"negative", `{"total":-1,"updated":-1}`, true},
{"conflict", `{"total":1,"updated":1,"version_conflicts":1}`, true},
{"timeout", `{"total":1,"updated":1,"timed_out":true}`, true},
} {
t.Run(tt.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Elastic-Product", "Elasticsearch")
if r.URL.Path == "/" {
_, _ = w.Write(
[]byte(
`{"version":{"number":"7.17.0","build_flavor":"default"},"tagline":"You Know, for Search"}`,
),
)
return
}
if r.URL.Path != "/vectors/_update_by_query" {
t.Errorf("unexpected path: %s", r.URL.Path)
}
_, _ = w.Write([]byte(tt.body))
}))
defer server.Close()
client, err := elasticsearch.NewTypedClient(
elasticsearch.Config{Addresses: []string{server.URL}, DisableRetry: true},
)
require.NoError(t, err)
repo := &elasticsearchRepository{client: client, index: "vectors"}
err = repo.MoveKnowledgeIndices(context.Background(), "source", "target", "doc", nil, 3, "file")
if tt.fails {
require.Error(t, err)
} else {
require.NoError(t, err)
}
})
}
}
@@ -0,0 +1,897 @@
package v8
import (
"context"
"encoding/json"
"fmt"
"strings"
elasticsearchRetriever "academy/internal/application/repository/retriever/elasticsearch"
"academy/internal/config"
"academy/internal/logger"
typesLocal "academy/internal/types"
"academy/internal/types/interfaces"
"github.com/elastic/go-elasticsearch/v8"
"github.com/elastic/go-elasticsearch/v8/typedapi/core/bulk"
"github.com/elastic/go-elasticsearch/v8/typedapi/core/search"
"github.com/elastic/go-elasticsearch/v8/typedapi/types"
"github.com/elastic/go-elasticsearch/v8/typedapi/types/enums/scriptlanguage"
"github.com/google/uuid"
)
// elasticsearchRepository implements the RetrieveEngineRepository interface for Elasticsearch v8
type elasticsearchRepository struct {
client *elasticsearch.TypedClient // Elasticsearch client instance
index string // Name of the Elasticsearch index to use
useKeywordSuffix bool // Whether to append .keyword suffix to ID field names in queries
numberOfShards int // Shard count for index creation (0 = ES default)
numberOfReplicas int // Replica count for index creation (-1 = unset, use ES default)
}
// NewElasticsearchEngineRepository creates and initializes a new Elasticsearch v8 repository.
// indexCfg is optional — pass nil to use env var / default values (env path).
func NewElasticsearchEngineRepository(client *elasticsearch.TypedClient,
config *config.Config,
indexCfg *typesLocal.IndexConfig,
) interfaces.RetrieveEngineRepository {
log := logger.GetLogger(context.Background())
log.Info("[Elasticsearch] Initializing Elasticsearch v8 retriever engine repository")
indexName := typesLocal.ResolveIndexName(indexCfg, "ELASTICSEARCH_INDEX", "xwrag_default")
// Create repository instance and ensure index exists
res := &elasticsearchRepository{
client: client,
index: indexName,
numberOfShards: indexCfg.GetNumberOfShards(0),
numberOfReplicas: indexCfg.GetNumberOfReplicas(-1),
}
if err := res.createIndexIfNotExists(context.Background()); err != nil {
log.Errorf("[Elasticsearch] Failed to create index: %v", err)
} else {
log.Info("[Elasticsearch] Successfully initialized repository")
}
res.detectFieldTypes(context.Background())
return res
}
// idField returns the query field name for an ID field, appending ".keyword"
// suffix when the index uses text-type mappings with keyword sub-fields.
func (e *elasticsearchRepository) idField(name string) string {
if e.useKeywordSuffix {
return name + ".keyword"
}
return name
}
// detectFieldTypes inspects the index mapping to determine whether ID fields
// are mapped as "keyword" (no suffix needed) or "text" (needs ".keyword" suffix).
func (e *elasticsearchRepository) detectFieldTypes(ctx context.Context) {
log := logger.GetLogger(ctx)
mappingResp, err := e.client.Indices.GetMapping().Index(e.index).Do(ctx)
if err != nil {
log.Warnf("[Elasticsearch] Failed to get index mapping, defaulting to .keyword suffix: %v", err)
e.useKeywordSuffix = true
return
}
indexMapping, ok := mappingResp[e.index]
if !ok {
log.Warnf("[Elasticsearch] Index %s not found in mapping response, defaulting to .keyword suffix", e.index)
e.useKeywordSuffix = true
return
}
if prop, ok := indexMapping.Mappings.Properties["chunk_id"]; ok {
propBytes, err := json.Marshal(prop)
if err == nil {
var propInfo struct {
Type string `json:"type"`
}
if json.Unmarshal(propBytes, &propInfo) == nil && propInfo.Type == "keyword" {
e.useKeywordSuffix = false
log.Infof("[Elasticsearch] Detected keyword type for ID fields, querying without .keyword suffix")
return
}
}
e.useKeywordSuffix = true
log.Infof("[Elasticsearch] ID fields are not keyword type, querying with .keyword suffix")
return
}
log.Infof("[Elasticsearch] No mapping detected for chunk_id (empty index?), defaulting to .keyword suffix")
e.useKeywordSuffix = true
}
// EngineType returns the type of retriever engine (Elasticsearch)
func (e *elasticsearchRepository) EngineType() typesLocal.RetrieverEngineType {
return typesLocal.ElasticsearchRetrieverEngineType
}
// Support returns the retrieval types supported by this repository (Keywords and Vector)
func (e *elasticsearchRepository) Support() []typesLocal.RetrieverType {
return []typesLocal.RetrieverType{typesLocal.KeywordsRetrieverType, typesLocal.VectorRetrieverType}
}
// calculateStorageSize estimates the storage size in bytes for a single index document
func (e *elasticsearchRepository) calculateStorageSize(embedding *elasticsearchRetriever.VectorEmbedding) int64 {
// 1. Content text size
contentSizeBytes := int64(len(embedding.Content))
// 2. Vector embedding size
var vectorSizeBytes int64 = 0
if embedding.Embedding != nil {
// 4 bytes per dimension (full precision float)
vectorSizeBytes = int64(len(embedding.Embedding) * 4)
}
// 3. Metadata size (IDs, timestamps, and other fixed overhead)
metadataSizeBytes := int64(250) // Approximately 250 bytes of metadata
// 4. Index overhead (Elasticsearch index expansion factor ~1.5)
indexOverheadBytes := (contentSizeBytes + vectorSizeBytes) * 5 / 10
// Total size in bytes
totalSizeBytes := contentSizeBytes + vectorSizeBytes + metadataSizeBytes + indexOverheadBytes
return totalSizeBytes
}
// EstimateStorageSize calculates the estimated storage size for a list of indices
// Returns the total size in bytes
func (e *elasticsearchRepository) EstimateStorageSize(ctx context.Context,
indexInfoList []*typesLocal.IndexInfo, params map[string]any,
) int64 {
var totalStorageSize int64 = 0
for _, embedding := range indexInfoList {
embeddingDB := elasticsearchRetriever.ToDBVectorEmbedding(embedding, params)
totalStorageSize += e.calculateStorageSize(embeddingDB)
}
logger.GetLogger(ctx).Infof(
"[Elasticsearch] Storage size for %d indices: %d bytes", len(indexInfoList), totalStorageSize,
)
return totalStorageSize
}
// Save stores a single index document in Elasticsearch
// Returns an error if the operation fails
func (e *elasticsearchRepository) Save(ctx context.Context,
embedding *typesLocal.IndexInfo,
additionalParams map[string]any,
) error {
log := logger.GetLogger(ctx)
log.Debugf("[Elasticsearch] Saving index for chunk ID: %s", embedding.ChunkID)
// Convert to database format
embeddingDB := elasticsearchRetriever.ToDBVectorEmbedding(embedding, additionalParams)
if len(embeddingDB.Embedding) == 0 {
err := fmt.Errorf("empty embedding vector for chunk ID: %s", embedding.ChunkID)
log.Errorf("[Elasticsearch] %v", err)
return err
}
// Index the document
resp, err := e.client.Index(e.index).Request(embeddingDB).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to save index: %v", err)
return err
}
log.Infof("[Elasticsearch] Successfully saved index for chunk ID: %s, document ID: %s", embedding.ChunkID, resp.Id_)
return nil
}
// BatchSave stores multiple index documents in Elasticsearch using bulk API
// Returns an error if the operation fails
func (e *elasticsearchRepository) BatchSave(ctx context.Context,
embeddingList []*typesLocal.IndexInfo, additionalParams map[string]any,
) error {
log := logger.GetLogger(ctx)
if len(embeddingList) == 0 {
log.Warn("[Elasticsearch] Empty list provided to BatchSave, skipping")
return nil
}
log.Infof("[Elasticsearch] Batch saving %d indices", len(embeddingList))
indexRequest := e.client.Bulk().Index(e.index)
// Add each document to the bulk request
for _, embedding := range embeddingList {
embeddingDB := elasticsearchRetriever.ToDBVectorEmbedding(embedding, additionalParams)
err := indexRequest.CreateOp(types.CreateOperation{Index_: &e.index}, embeddingDB)
if err != nil {
log.Errorf("[Elasticsearch] Failed to create bulk operation: %v", err)
return fmt.Errorf("failed to create op: %w", err)
}
log.Debugf("[Elasticsearch] Added chunk ID %s to bulk request", embedding.ChunkID)
}
// Execute the bulk request. Elasticsearch answers an accepted _bulk call
// with HTTP 200 even when it rejects individual documents, so the
// per-item errors in the response body are the only failure signal.
resp, err := indexRequest.Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to execute bulk operation: %v", err)
return fmt.Errorf("failed to do bulk: %w", err)
}
if err := inspectBulkResponse(ctx, resp); err != nil {
return err
}
log.Infof("[Elasticsearch] Successfully batch saved %d indices", len(embeddingList))
return nil
}
// bulkErrorSummaryLimit caps how many per-item failures are described in the
// returned error; the reported count always covers every failed item.
const bulkErrorSummaryLimit = 5
// inspectBulkResponse converts per-item _bulk failures into an error. A bulk
// request that the server accepted answers HTTP 200, so a document rejected
// for a mapping mismatch, a read-only index or an item-level rejection is
// visible only in the response body.
//
// The error names the document _id and the bounded error.type of up to
// bulkErrorSummaryLimit failed items. error.reason is deliberately excluded
// because it can embed document content.
func inspectBulkResponse(ctx context.Context, resp *bulk.Response) error {
if resp == nil || !resp.Errors {
return nil
}
log := logger.GetLogger(ctx)
msgs := make([]string, 0, bulkErrorSummaryLimit)
failed := 0
for _, item := range resp.Items {
for op, detail := range item {
if detail.Error == nil {
continue
}
failed++
id := ""
if detail.Id_ != nil {
id = *detail.Id_
}
log.Debugf("[Elasticsearch] Bulk item failed: op=%s id=%s type=%s",
op, id, detail.Error.Type)
if len(msgs) < bulkErrorSummaryLimit {
msgs = append(msgs, fmt.Sprintf("[%s %s] %s", op, id, detail.Error.Type))
}
}
}
if failed == 0 {
return fmt.Errorf("elasticsearch: bulk reported errors without per-item failure detail")
}
return fmt.Errorf("elasticsearch: bulk partial failure (%d/%d documents failed, first %d: %s)",
failed, len(resp.Items), len(msgs), strings.Join(msgs, "; "))
}
// DeleteByChunkIDList removes documents from the index based on chunk IDs
// Returns an error if the delete operation fails
func (e *elasticsearchRepository) DeleteByChunkIDList(ctx context.Context, chunkIDList []string, dimension int, knowledgeType string) error {
log := logger.GetLogger(ctx)
if len(chunkIDList) == 0 {
log.Warn("[Elasticsearch] Empty chunk ID list provided for deletion, skipping")
return nil
}
log.Infof("[Elasticsearch] Deleting indices by chunk IDs, count: %d", len(chunkIDList))
// Use DeleteByQuery to delete all documents matching the chunk IDs
_, err := e.client.DeleteByQuery(e.index).Query(&types.Query{
Terms: &types.TermsQuery{TermsQuery: map[string]types.TermsQueryField{e.idField("chunk_id"): chunkIDList}},
}).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to delete by chunk IDs: %v", err)
return fmt.Errorf("failed to delete by query: %w", err)
}
log.Infof("[Elasticsearch] Successfully deleted documents by chunk IDs")
return nil
}
// DeleteBySourceIDList removes documents from the index based on source IDs
// Returns an error if the delete operation fails
func (e *elasticsearchRepository) DeleteBySourceIDList(ctx context.Context, sourceIDList []string, dimension int, knowledgeType string) error {
log := logger.GetLogger(ctx)
if len(sourceIDList) == 0 {
log.Warn("[Elasticsearch] Empty source ID list provided for deletion, skipping")
return nil
}
log.Infof("[Elasticsearch] Deleting indices by source IDs, count: %d", len(sourceIDList))
// Use DeleteByQuery to delete all documents matching the source IDs
_, err := e.client.DeleteByQuery(e.index).Query(&types.Query{
Terms: &types.TermsQuery{TermsQuery: map[string]types.TermsQueryField{e.idField("source_id"): sourceIDList}},
}).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to delete by source IDs: %v", err)
return fmt.Errorf("failed to delete by query: %w", err)
}
log.Infof("[Elasticsearch] Successfully deleted documents by source IDs")
return nil
}
// DeleteByKnowledgeIDList removes documents from the index based on knowledge IDs
// Returns an error if the delete operation fails
func (e *elasticsearchRepository) DeleteByKnowledgeIDList(ctx context.Context,
knowledgeIDList []string, dimension int, knowledgeType string,
) error {
log := logger.GetLogger(ctx)
if len(knowledgeIDList) == 0 {
log.Warn("[Elasticsearch] Empty knowledge ID list provided for deletion, skipping")
return nil
}
log.Infof("[Elasticsearch] Deleting indices by knowledge IDs, count: %d", len(knowledgeIDList))
// Use DeleteByQuery to delete all documents matching the knowledge IDs
_, err := e.client.DeleteByQuery(e.index).Query(&types.Query{
Terms: &types.TermsQuery{TermsQuery: map[string]types.TermsQueryField{e.idField("knowledge_id"): knowledgeIDList}},
}).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to delete by knowledge IDs: %v", err)
return fmt.Errorf("failed to delete by query: %w", err)
}
log.Infof("[Elasticsearch] Successfully deleted documents by knowledge IDs")
return nil
}
// getBaseConds creates the base query conditions for retrieval operations
// Returns a slice of Query objects with must and must_not conditions
// KnowledgeBaseIDs and KnowledgeIDs use AND logic (search specific documents within knowledge bases)
func (e *elasticsearchRepository) getBaseConds(params typesLocal.RetrieveParams) []types.Query {
must := []types.Query{}
// KnowledgeBaseIDs and KnowledgeIDs use AND logic
// - If only KnowledgeBaseIDs: search entire knowledge bases
// - If only KnowledgeIDs: search specific documents
// - If both: search specific documents within the knowledge bases (AND)
if len(params.KnowledgeBaseIDs) > 0 {
must = append(must, types.Query{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{
e.idField("knowledge_base_id"): params.KnowledgeBaseIDs,
},
}})
}
if len(params.KnowledgeIDs) > 0 {
must = append(must, types.Query{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{
e.idField("knowledge_id"): params.KnowledgeIDs,
},
}})
}
// Filter by tag IDs if specified
if len(params.TagIDs) > 0 {
must = append(must, types.Query{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{
e.idField("tag_id"): params.TagIDs,
},
}})
}
mustNot := make([]types.Query, 0)
// Exclude disabled chunks (is_enabled = false)
// Note: Historical data without is_enabled field will be included (not matching must_not)
mustNot = append(mustNot, types.Query{Term: map[string]types.TermQuery{
"is_enabled": {Value: false},
}})
if len(params.ExcludeKnowledgeIDs) > 0 {
mustNot = append(mustNot, types.Query{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{e.idField("knowledge_id"): params.ExcludeKnowledgeIDs},
}})
}
if len(params.ExcludeChunkIDs) > 0 {
mustNot = append(mustNot, types.Query{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{e.idField("chunk_id"): params.ExcludeChunkIDs},
}})
}
return []types.Query{{Bool: &types.BoolQuery{Must: must, MustNot: mustNot}}}
}
// createIndexIfNotExists checks if the specified index exists and creates it if not
// Returns an error if the operation fails
func (e *elasticsearchRepository) createIndexIfNotExists(ctx context.Context) error {
log := logger.GetLogger(ctx)
log.Debugf("[Elasticsearch] Checking if index exists: %s", e.index)
// Check if index exists
exists, err := e.client.Indices.Exists(e.index).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to check if index exists: %v", err)
return err
}
if exists {
log.Debugf("[Elasticsearch] Index already exists: %s", e.index)
return nil
}
// Create index if it doesn't exist, with optional shards/replicas settings
log.Infof("[Elasticsearch] Creating index: %s", e.index)
createReq := e.client.Indices.Create(e.index)
if e.numberOfShards > 0 || e.numberOfReplicas >= 0 {
settings := &types.IndexSettings{}
if e.numberOfShards > 0 {
shards := fmt.Sprintf("%d", e.numberOfShards)
settings.NumberOfShards = &shards
}
if e.numberOfReplicas >= 0 {
replicas := fmt.Sprintf("%d", e.numberOfReplicas)
settings.NumberOfReplicas = &replicas
}
createReq = createReq.Settings(settings)
}
_, err = createReq.Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to create index: %v", err)
return err
}
log.Infof("[Elasticsearch] Index created successfully: %s", e.index)
return nil
}
// Retrieve dispatches the retrieval operation to the appropriate method based on retriever type
// Returns a slice of RetrieveResult and an error if the operation fails
func (e *elasticsearchRepository) Retrieve(ctx context.Context,
params typesLocal.RetrieveParams,
) ([]*typesLocal.RetrieveResult, error) {
log := logger.GetLogger(ctx)
log.Debugf("[Elasticsearch] Processing retrieval request of type: %s", params.RetrieverType)
// Route to appropriate retrieval method
switch params.RetrieverType {
case typesLocal.VectorRetrieverType:
return e.VectorRetrieve(ctx, params)
case typesLocal.KeywordsRetrieverType:
return e.KeywordsRetrieve(ctx, params)
}
err := fmt.Errorf("invalid retriever type: %v", params.RetrieverType)
log.Errorf("[Elasticsearch] %v", err)
return nil, err
}
// vectorScoreScriptSource scores every document by its cosine similarity to the
// query vector, floored at 0. Lucene rejects negative final script_score values
// ("script_score script returned an invalid score ... Must be a non-negative
// score!"), so an unclamped negative cosine — which occurs whenever any stored
// vector points away from the query — fails the entire search request with a
// 400 (all shards failed) instead of merely ranking that document last. The
// floor keeps the score in the [0, 1] range the shared retriever score
// normalizer documents for this engine; documents clamped to 0 fall below any
// positive min_score threshold.
var vectorScoreScriptSource = "Math.max(cosineSimilarity(params.query_vector, 'embedding'), 0.0)"
// buildVectorScriptScoreQuery wraps the cosine-similarity scoring script in a
// script_score query over the request's base filter conditions.
func (e *elasticsearchRepository) buildVectorScriptScoreQuery(
params typesLocal.RetrieveParams,
) (*types.ScriptScoreQuery, error) {
queryVectorJSON, err := json.Marshal(params.Embedding)
if err != nil {
return nil, fmt.Errorf("failed to marshal query embedding: %w", err)
}
minScore := float32(params.Threshold)
return &types.ScriptScoreQuery{
Query: types.Query{Bool: &types.BoolQuery{Filter: e.getBaseConds(params)}},
Script: types.Script{
Source: &vectorScoreScriptSource,
Params: map[string]json.RawMessage{
"query_vector": json.RawMessage(queryVectorJSON),
},
},
MinScore: &minScore,
}, nil
}
// VectorRetrieve performs vector similarity search using cosine similarity
// Returns a slice of RetrieveResult containing matching documents
func (e *elasticsearchRepository) VectorRetrieve(ctx context.Context,
params typesLocal.RetrieveParams,
) ([]*typesLocal.RetrieveResult, error) {
log := logger.GetLogger(ctx)
log.Infof("[Elasticsearch] Vector retrieval: dim=%d, topK=%d, threshold=%.4f",
len(params.Embedding), params.TopK, params.Threshold)
scriptScore, err := e.buildVectorScriptScoreQuery(params)
if err != nil {
log.Errorf("[Elasticsearch] Failed to marshal query vector: %v", err)
return nil, err
}
// Exclude embedding field from source to reduce response size
sourceFilter := &types.SourceFilter{
Excludes: []string{"embedding"},
}
log.Debugf("[Elasticsearch] Executing vector search in index: %s", e.index)
// Execute search with minimum score threshold
response, err := e.client.Search().Index(e.index).Request(&search.Request{
Query: &types.Query{ScriptScore: scriptScore},
Size: &params.TopK,
Source_: sourceFilter,
}).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Vector search failed: %v", err)
return nil, err
}
// Process search results
var results []*typesLocal.IndexWithScore
for _, hit := range response.Hits.Hits {
var embedding *elasticsearchRetriever.VectorEmbeddingWithScore
if err := json.Unmarshal(hit.Source_, &embedding); err != nil {
log.Errorf("[Elasticsearch] Failed to unmarshal search result: %v", err)
return nil, err
}
embedding.Score = float64(*hit.Score_)
results = append(results,
elasticsearchRetriever.FromDBVectorEmbeddingWithScore(*hit.Id_, embedding, typesLocal.MatchTypeEmbedding))
}
if len(results) == 0 {
log.Warnf("[Elasticsearch] No vector matches found that meet threshold %.4f", params.Threshold)
} else {
log.Infof("[Elasticsearch] Vector retrieval found %d results", len(results))
log.Debugf("[Elasticsearch] Top result score: %.4f", results[0].Score)
}
return []*typesLocal.RetrieveResult{
{
Results: results,
RetrieverEngineType: typesLocal.ElasticsearchRetrieverEngineType,
RetrieverType: typesLocal.VectorRetrieverType,
Error: nil,
},
}, nil
}
// KeywordsRetrieve performs keyword-based search in document content
// Returns a slice of RetrieveResult containing matching documents
func (e *elasticsearchRepository) KeywordsRetrieve(ctx context.Context,
params typesLocal.RetrieveParams,
) ([]*typesLocal.RetrieveResult, error) {
log := logger.GetLogger(ctx)
log.Infof("[Elasticsearch] Performing keywords retrieval with query: %s, topK: %d", params.Query, params.TopK)
filter := e.getBaseConds(params)
// Build must conditions for content matching
must := []types.Query{
{Match: map[string]types.MatchQuery{"content": {Query: params.Query}}},
}
// Exclude embedding field from source to reduce response size
sourceFilter := &types.SourceFilter{
Excludes: []string{"embedding"},
}
log.Debugf("[Elasticsearch] Executing keyword search in index: %s", e.index)
response, err := e.client.Search().Index(e.index).Request(&search.Request{
Query: &types.Query{Bool: &types.BoolQuery{Filter: filter, Must: must}},
Size: &params.TopK,
Source_: sourceFilter,
}).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Keywords search failed: %v", err)
return nil, err
}
// Process search results
var results []*typesLocal.IndexWithScore
for _, hit := range response.Hits.Hits {
var embedding *elasticsearchRetriever.VectorEmbeddingWithScore
if err := json.Unmarshal(hit.Source_, &embedding); err != nil {
log.Errorf("[Elasticsearch] Failed to unmarshal search result: %v", err)
return nil, err
}
embedding.Score = float64(*hit.Score_)
results = append(results,
elasticsearchRetriever.FromDBVectorEmbeddingWithScore(*hit.Id_, embedding, typesLocal.MatchTypeKeywords),
)
}
if len(results) == 0 {
log.Warnf("[Elasticsearch] No keyword matches found for query: %s", params.Query)
} else {
log.Infof("[Elasticsearch] Keywords retrieval found %d results", len(results))
log.Debugf("[Elasticsearch] Top result score: %.4f", results[0].Score)
}
return []*typesLocal.RetrieveResult{
{
Results: results,
RetrieverEngineType: typesLocal.ElasticsearchRetrieverEngineType,
RetrieverType: typesLocal.KeywordsRetrieverType,
Error: nil,
},
}, nil
}
// copySourceDoc decodes a source row for CopyIndices. IsEnabled shadows the
// embedded field so a row written before is_enabled existed, which retrieval
// treats as enabled, can be told apart from an explicit false.
type copySourceDoc struct {
elasticsearchRetriever.VectorEmbedding
IsEnabled *bool `json:"is_enabled"`
}
// CopyIndices 复制索引数据
func (e *elasticsearchRepository) CopyIndices(ctx context.Context,
sourceKnowledgeBaseID string,
sourceToTargetKBIDMap map[string]string,
sourceToTargetChunkIDMap map[string]string,
targetKnowledgeBaseID string,
dimension int,
knowledgeType string,
) error {
log := logger.GetLogger(ctx)
log.Infof(
"[Elasticsearch] Copying indices from source knowledge base %s to target knowledge base %s, count: %d",
sourceKnowledgeBaseID, targetKnowledgeBaseID, len(sourceToTargetChunkIDMap),
)
if len(sourceToTargetChunkIDMap) == 0 {
log.Warn("[Elasticsearch] Empty mapping, skipping copy")
return nil
}
// Scan every row of the source knowledge base. getBaseConds is not used
// here because it drops disabled rows, which must be copied as disabled.
filter := []types.Query{{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{
e.idField("knowledge_base_id"): []string{sourceKnowledgeBaseID},
},
}}}
// Set batch processing parameters
batchSize := 500
from := 0
totalCopied := 0
for {
// Execute pagination query
searchResponse, err := e.client.Search().Index(e.index).
Query(&types.Query{Bool: &types.BoolQuery{Filter: filter}}).
From(from).
Size(batchSize).
Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to query source index data: %v", err)
return err
}
hitsCount := len(searchResponse.Hits.Hits)
if hitsCount == 0 {
break
}
log.Infof("[Elasticsearch] Found %d source index data, batch start position: %d", hitsCount, from)
// Prepare index list for BatchSave
var indexInfoList []*typesLocal.IndexInfo
// Collect all embedding vector data for additionalParams
embeddingMap := make(map[string][]float32)
for _, hit := range searchResponse.Hits.Hits {
// Parse source document
var sourceDoc copySourceDoc
if err := json.Unmarshal(hit.Source_, &sourceDoc); err != nil {
log.Errorf("[Elasticsearch] Failed to parse source index data: %v", err)
continue
}
// Get mapped target chunk ID and knowledge ID
targetChunkID, ok := sourceToTargetChunkIDMap[sourceDoc.ChunkID]
if !ok {
log.Warnf("[Elasticsearch] Source chunk %s not found in target mapping, skipping", sourceDoc.ChunkID)
continue
}
targetKnowledgeID, ok := sourceToTargetKBIDMap[sourceDoc.KnowledgeID]
if !ok {
log.Warnf(
"[Elasticsearch] Source knowledge %s not found in target mapping, skipping",
sourceDoc.KnowledgeID,
)
continue
}
// Handle SourceID transformation for generated questions
// Generated questions have SourceID format: {chunkID}-{questionID}
// Regular chunks have SourceID == ChunkID
var targetSourceID string
if sourceDoc.SourceID == sourceDoc.ChunkID {
// Regular chunk, use targetChunkID as SourceID
targetSourceID = targetChunkID
} else if strings.HasPrefix(sourceDoc.SourceID, sourceDoc.ChunkID+"-") {
// This is a generated question, preserve the questionID part
questionID := strings.TrimPrefix(sourceDoc.SourceID, sourceDoc.ChunkID+"-")
targetSourceID = fmt.Sprintf("%s-%s", targetChunkID, questionID)
} else {
// For other complex scenarios, generate new unique SourceID
targetSourceID = uuid.New().String()
}
// BatchSave looks embeddings up by SourceID, so key by the target
// SourceID; rows of one chunk would collide on the chunk ID.
if len(sourceDoc.Embedding) > 0 {
embeddingMap[targetSourceID] = sourceDoc.Embedding
}
// Create new index information
indexInfo := &typesLocal.IndexInfo{
Content: sourceDoc.Content,
SourceID: targetSourceID,
SourceType: typesLocal.SourceType(sourceDoc.SourceType),
ChunkID: targetChunkID,
KnowledgeID: targetKnowledgeID,
KnowledgeBaseID: targetKnowledgeBaseID,
IsEnabled: sourceDoc.IsEnabled == nil || *sourceDoc.IsEnabled,
}
indexInfoList = append(indexInfoList, indexInfo)
totalCopied++
}
// Use BatchSave function to save index
if len(indexInfoList) > 0 {
// Add embedding vector to additional parameters
additionalParams := map[string]any{
"embedding": embeddingMap,
}
if err := e.BatchSave(ctx, indexInfoList, additionalParams); err != nil {
log.Errorf("[Elasticsearch] Failed to batch save index: %v", err)
return err
}
log.Infof("[Elasticsearch] Successfully copied batch data, batch size: %d, total copied: %d",
len(indexInfoList), totalCopied)
}
// Move to next batch
from += hitsCount
// If the number of returned records is less than the request size, it means the last page has been reached
if hitsCount < batchSize {
break
}
}
log.Infof("[Elasticsearch] Index copy completed, total copied: %d", totalCopied)
return nil
}
// BatchUpdateChunkEnabledStatus updates the enabled status of chunks in batch
func (e *elasticsearchRepository) BatchUpdateChunkEnabledStatus(
ctx context.Context,
chunkStatusMap map[string]bool,
) error {
log := logger.GetLogger(ctx)
if len(chunkStatusMap) == 0 {
log.Warnf("[Elasticsearch] Chunk status map is empty, skipping update")
return nil
}
log.Infof("[Elasticsearch] Batch updating chunk enabled status, count: %d", len(chunkStatusMap))
// Group chunks by enabled status for batch updates
enabledChunkIDs := make([]string, 0)
disabledChunkIDs := make([]string, 0)
for chunkID, enabled := range chunkStatusMap {
if enabled {
enabledChunkIDs = append(enabledChunkIDs, chunkID)
} else {
disabledChunkIDs = append(disabledChunkIDs, chunkID)
}
}
// Batch update enabled chunks using update_by_query
if len(enabledChunkIDs) > 0 {
query := types.NewQuery()
query.Bool = &types.BoolQuery{
Must: []types.Query{
{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{
e.idField("chunk_id"): enabledChunkIDs,
},
}},
},
}
source := "ctx._source.is_enabled = true"
lang := scriptlanguage.Painless
script := types.Script{
Source: &source,
Lang: &lang,
}
_, err := e.client.UpdateByQuery(e.index).Query(query).Script(&script).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to update enabled chunks: %v", err)
return err
}
log.Infof("[Elasticsearch] Updated %d chunks to enabled", len(enabledChunkIDs))
}
// Batch update disabled chunks using update_by_query
if len(disabledChunkIDs) > 0 {
query := types.NewQuery()
query.Bool = &types.BoolQuery{
Must: []types.Query{
{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{
e.idField("chunk_id"): disabledChunkIDs,
},
}},
},
}
source := "ctx._source.is_enabled = false"
lang := scriptlanguage.Painless
script := types.Script{
Source: &source,
Lang: &lang,
}
_, err := e.client.UpdateByQuery(e.index).Query(query).Script(&script).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to update disabled chunks: %v", err)
return err
}
log.Infof("[Elasticsearch] Updated %d chunks to disabled", len(disabledChunkIDs))
}
log.Infof("[Elasticsearch] Successfully batch updated chunk enabled status")
return nil
}
// BatchUpdateChunkTagID updates the tag ID of chunks in batch
func (e *elasticsearchRepository) BatchUpdateChunkTagID(
ctx context.Context,
chunkTagMap map[string]string,
) error {
log := logger.GetLogger(ctx)
if len(chunkTagMap) == 0 {
log.Warnf("[Elasticsearch] Chunk tag map is empty, skipping update")
return nil
}
log.Infof("[Elasticsearch] Batch updating chunk tag ID, count: %d", len(chunkTagMap))
// Group chunks by tag ID for batch updates
tagGroups := make(map[string][]string)
for chunkID, tagID := range chunkTagMap {
tagGroups[tagID] = append(tagGroups[tagID], chunkID)
}
// Batch update chunks for each tag ID using update_by_query
for tagID, chunkIDs := range tagGroups {
query := types.NewQuery()
query.Bool = &types.BoolQuery{
Must: []types.Query{
{Terms: &types.TermsQuery{
TermsQuery: map[string]types.TermsQueryField{
e.idField("chunk_id"): chunkIDs,
},
}},
},
}
source := "ctx._source.tag_id = params.tag_id"
lang := scriptlanguage.Painless
script := types.Script{
Source: &source,
Lang: &lang,
Params: map[string]json.RawMessage{
"tag_id": json.RawMessage(`"` + tagID + `"`),
},
}
_, err := e.client.UpdateByQuery(e.index).Query(query).Script(&script).Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to update chunks with tag_id %s: %v", tagID, err)
return err
}
log.Infof("[Elasticsearch] Updated %d chunks to tag_id=%s", len(chunkIDs), tagID)
}
log.Infof("[Elasticsearch] Successfully batch updated chunk tag ID")
return nil
}
@@ -0,0 +1,49 @@
package v8
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
typesLocal "academy/internal/types"
)
// Regression test for #3156: the script_score source must floor the cosine
// similarity at 0. An unclamped negative cosine makes Lucene reject the whole
// search request ("script_score script returned an invalid score ... Must be a
// non-negative score!"), turning one dissimilar document into a full vector
// retrieval outage (all shards failed).
func TestVectorScoreScriptSourceClampsNegativeCosine(t *testing.T) {
require.Equal(t,
"Math.max(cosineSimilarity(params.query_vector, 'embedding'), 0.0)",
vectorScoreScriptSource)
}
func TestBuildVectorScriptScoreQuery(t *testing.T) {
e := &elasticsearchRepository{}
params := typesLocal.RetrieveParams{
Embedding: []float32{1, 0},
Threshold: 0.15,
TopK: 10,
KnowledgeBaseIDs: []string{"kb-1"},
}
q, err := e.buildVectorScriptScoreQuery(params)
require.NoError(t, err)
require.NotNil(t, q)
require.NotNil(t, q.Script.Source)
require.Equal(t, vectorScoreScriptSource, *q.Script.Source)
require.NotNil(t, q.MinScore)
require.InDelta(t, 0.15, float64(*q.MinScore), 1e-6)
require.NotNil(t, q.Query.Bool)
require.Len(t, q.Query.Bool.Filter, 1)
var queryVector []float32
require.NotNil(t, q.Script.Params["query_vector"])
require.NoError(t, json.Unmarshal(q.Script.Params["query_vector"], &queryVector))
require.Equal(t, []float32{1, 0}, queryVector)
}