diff --git a/sundynix-mcp-go/internal/rag/milvus.go b/sundynix-mcp-go/internal/rag/milvus.go index 3ca1a1f..58d37b9 100644 --- a/sundynix-mcp-go/internal/rag/milvus.go +++ b/sundynix-mcp-go/internal/rag/milvus.go @@ -3,6 +3,8 @@ package rag import ( "context" "fmt" + "log" + "strconv" "sync" "github.com/milvus-io/milvus-sdk-go/v2/client" @@ -44,6 +46,18 @@ func (m *milvusStore) ensure(ctx context.Context, dim int) error { if err != nil { return err } + // 已存集合维度不一致(如切换 embedding 模型)→ 重建。 + if has { + if coll, derr := m.cli.DescribeCollection(ctx, collection); derr == nil { + if existing := vectorDim(coll); existing != 0 && existing != dim { + log.Printf("[rag] 集合维度 %d≠%d,重建 %s", existing, dim, collection) + if err := m.cli.DropCollection(ctx, collection); err != nil { + return fmt.Errorf("drop collection: %w", err) + } + has = false + } + } + } if !has { schema := entity.NewSchema().WithName(collection).WithDescription("sundynix wiki vectors"). WithField(entity.NewField().WithName("id").WithDataType(entity.FieldTypeInt64).WithIsPrimaryKey(true).WithIsAutoID(true)). @@ -88,6 +102,22 @@ func (m *milvusStore) insert(ctx context.Context, kb string, texts []string, vec return m.cli.Flush(ctx, collection, false) } +// vectorDim 从集合 schema 读出向量字段维度(用于检测维度变化)。 +func vectorDim(coll *entity.Collection) int { + if coll == nil || coll.Schema == nil { + return 0 + } + for _, f := range coll.Schema.Fields { + if f.DataType == entity.FieldTypeFloatVector { + if d, ok := f.TypeParams["dim"]; ok { + n, _ := strconv.Atoi(d) + return n + } + } + } + return 0 +} + // Hit 是一条检索结果。 type Hit struct { Text string