feat: pass IndexConfig to repositories with scalability options

This commit is contained in:
ochan.kwon
2026-04-16 15:12:42 +09:00
committed by lyingbug
parent 7bd36bf954
commit 927d3debff
14 changed files with 673 additions and 69 deletions
@@ -12,7 +12,6 @@ import (
"encoding/json"
"errors"
"fmt"
"os"
"strings"
elasticsearchRetriever "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch"
@@ -29,22 +28,31 @@ type elasticsearchRepository struct {
client *elasticsearch.Client
index string
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 v7 repository.
// indexCfg is optional — pass nil to use env var / default values (env path).
func NewElasticsearchEngineRepository(client *elasticsearch.Client,
config *config.Config,
indexCfg *typesLocal.IndexConfig,
) interfaces.RetrieveEngineRepository {
log := logger.GetLogger(context.Background())
log.Info("[ElasticsearchV7] Initializing Elasticsearch v7 retriever engine repository")
indexName := os.Getenv("ELASTICSEARCH_INDEX")
if indexName == "" {
log.Warn("[ElasticsearchV7] ELASTICSEARCH_INDEX environment variable not set, using default index name")
indexName = "xwrag_default"
}
indexName := typesLocal.ResolveIndexName(indexCfg, "ELASTICSEARCH_INDEX", "xwrag_default")
log.Infof("[ElasticsearchV7] Using index: %s", indexName)
res := &elasticsearchRepository{client: client, index: indexName}
res := &elasticsearchRepository{
client: client,
index: indexName,
numberOfShards: indexCfg.GetNumberOfShards(0),
numberOfReplicas: indexCfg.GetNumberOfReplicas(-1),
}
if err := res.createIndexIfNotExists(context.Background()); err != nil {
log.Errorf("[ElasticsearchV7] Failed to create index: %v", err)
}
res.detectFieldTypes(context.Background())
return res
}
@@ -118,6 +126,63 @@ func (e *elasticsearchRepository) detectFieldTypes(ctx context.Context) {
}
}
// createIndexIfNotExists checks if the specified index exists and creates it if not.
// Uses esapi low-level client since v7 SDK does not have typed API.
func (e *elasticsearchRepository) createIndexIfNotExists(ctx context.Context) error {
log := logger.GetLogger(ctx)
log.Debugf("[ElasticsearchV7] Checking if index exists: %s", e.index)
res, err := e.client.Indices.Exists([]string{e.index}, e.client.Indices.Exists.WithContext(ctx))
if err != nil {
return fmt.Errorf("check index existence: %w", err)
}
defer res.Body.Close()
if !res.IsError() {
log.Debugf("[ElasticsearchV7] Index already exists: %s", e.index)
return nil
}
// Build settings body with optional shards/replicas
var body string
if e.numberOfShards > 0 || e.numberOfReplicas >= 0 {
settings := make(map[string]interface{})
if e.numberOfShards > 0 {
settings["number_of_shards"] = e.numberOfShards
}
if e.numberOfReplicas >= 0 {
settings["number_of_replicas"] = e.numberOfReplicas
}
bodyBytes, err := json.Marshal(map[string]interface{}{"settings": settings})
if err != nil {
return fmt.Errorf("marshal index settings: %w", err)
}
body = string(bodyBytes)
}
log.Infof("[ElasticsearchV7] Creating index: %s", e.index)
var opts []func(*esapi.IndicesCreateRequest)
opts = append(opts, e.client.Indices.Create.WithContext(ctx))
if body != "" {
opts = append(opts, e.client.Indices.Create.WithBody(strings.NewReader(body)))
}
createRes, err := e.client.Indices.Create(e.index, opts...)
if err != nil {
return fmt.Errorf("create index: %w", err)
}
defer createRes.Body.Close()
if createRes.IsError() {
// Log detailed response server-side; return generic message to avoid leaking cluster info
log.Errorf("[ElasticsearchV7] Create index response: %s", createRes.String())
return fmt.Errorf("failed to create index %s", e.index)
}
log.Infof("[ElasticsearchV7] Index created successfully: %s", e.index)
return nil
}
func (e *elasticsearchRepository) EngineType() typesLocal.RetrieverEngineType {
return typesLocal.ElasticsearchRetrieverEngineType
}
@@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"fmt"
"os"
"strings"
elasticsearchRetriever "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch"
@@ -24,25 +23,28 @@ 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
// It sets up the index and returns a repository instance ready for use
// 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")
// Get index name from environment variable or use default
indexName := os.Getenv("ELASTICSEARCH_INDEX")
if indexName == "" {
log.Warn("[Elasticsearch] ELASTICSEARCH_INDEX environment variable not set, using default index name")
indexName = "xwrag_default"
}
indexName := typesLocal.ResolveIndexName(indexCfg, "ELASTICSEARCH_INDEX", "xwrag_default")
// Create repository instance and ensure index exists
res := &elasticsearchRepository{client: client, index: indexName}
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 {
@@ -355,9 +357,20 @@ func (e *elasticsearchRepository) createIndexIfNotExists(ctx context.Context) er
return nil
}
// Create index if it doesn't exist
// Create index if it doesn't exist, with optional shards/replicas settings
log.Infof("[Elasticsearch] Creating index: %s", e.index)
_, err = e.client.Indices.Create(e.index).Do(ctx)
createReq := e.client.Indices.Create(e.index)
if e.numberOfShards > 0 || e.numberOfReplicas >= 0 {
settings := &types.IndexSettings{}
if e.numberOfShards > 0 {
settings.NumberOfShards = fmt.Sprintf("%d", e.numberOfShards)
}
if e.numberOfReplicas >= 0 {
settings.NumberOfReplicas = fmt.Sprintf("%d", e.numberOfReplicas)
}
createReq = createReq.Settings(settings)
}
_, err = createReq.Do(ctx)
if err != nil {
log.Errorf("[Elasticsearch] Failed to create index: %v", err)
return err
@@ -41,16 +41,13 @@ var (
fieldKnowledgeID, fieldKnowledgeBaseID, fieldTagID, fieldIsEnabled, fieldEmbedding}
)
// NewMilvusRetrieveEngineRepository creates and initializes a new Milvus repository
func NewMilvusRetrieveEngineRepository(client *client.Client) interfaces.RetrieveEngineRepository {
// NewMilvusRetrieveEngineRepository creates and initializes a new Milvus repository.
// indexCfg is optional — pass nil to use env var / default values (env path).
func NewMilvusRetrieveEngineRepository(client *client.Client, indexCfg *types.IndexConfig) interfaces.RetrieveEngineRepository {
log := logger.GetLogger(context.Background())
log.Info("[Milvus] Initializing Milvus retriever engine repository")
collectionBaseName := os.Getenv(envMilvusCollection)
if collectionBaseName == "" {
log.Warn("[Milvus] MILVUS_COLLECTION environment variable not set, using default collection name")
collectionBaseName = defaultCollectionName
}
collectionBaseName := types.ResolveCollectionName(indexCfg, envMilvusCollection, defaultCollectionName)
metricType := entity.IP
if mt := os.Getenv(envMilvusMetricType); mt != "" {
@@ -72,6 +69,8 @@ func NewMilvusRetrieveEngineRepository(client *client.Client) interfaces.Retriev
client: client,
collectionBaseName: collectionBaseName,
metricType: metricType,
shardsNum: indexCfg.GetShardsNum(0),
replicaNumber: indexCfg.GetReplicaNumber(0),
}
log.Info("[Milvus] Successfully initialized repository")
@@ -176,7 +175,11 @@ func (m *milvusRepository) ensureCollection(ctx context.Context, dimension int)
}
// Create collection
err = m.client.CreateCollection(ctx, client.NewCreateCollectionOption(collectionName, schema).WithIndexOptions(indexOpts...))
createOpt := client.NewCreateCollectionOption(collectionName, schema).WithIndexOptions(indexOpts...)
if m.shardsNum > 0 {
createOpt = createOpt.WithShardNum(int32(m.shardsNum))
}
err = m.client.CreateCollection(ctx, createOpt)
if err != nil {
log.Errorf("[Milvus] Failed to create collection: %v", err)
return fmt.Errorf("failed to create collection: %w", err)
@@ -185,7 +188,11 @@ func (m *milvusRepository) ensureCollection(ctx context.Context, dimension int)
log.Infof("[Milvus] Successfully created collection %s", collectionName)
}
loadTask, err := m.client.LoadCollection(ctx, client.NewLoadCollectionOption(collectionName))
loadOpt := client.NewLoadCollectionOption(collectionName)
if m.replicaNumber > 0 {
loadOpt = loadOpt.WithReplica(m.replicaNumber)
}
loadTask, err := m.client.LoadCollection(ctx, loadOpt)
if err != nil {
log.Errorf("[Milvus] Failed to load collection: %v", err)
return fmt.Errorf("failed to load collection: %w", err)
@@ -12,6 +12,8 @@ type milvusRepository struct {
client *client.Client
collectionBaseName string
metricType entity.MetricType
shardsNum int // 0 = use Milvus default (1)
replicaNumber int // 0 = use Milvus default (1); set at LoadCollection time
// Cache for initialized collections (dimension -> true)
initializedCollections sync.Map
}
@@ -4,7 +4,6 @@ import (
"context"
"fmt"
"maps"
"os"
"slices"
"strings"
"unicode/utf8"
@@ -30,20 +29,19 @@ const (
fieldIsEnabled = "is_enabled"
)
// NewQdrantRetrieveEngineRepository creates and initializes a new Qdrant repository
func NewQdrantRetrieveEngineRepository(client *qdrant.Client) interfaces.RetrieveEngineRepository {
// NewQdrantRetrieveEngineRepository creates and initializes a new Qdrant repository.
// indexCfg is optional — pass nil to use env var / default values (env path).
func NewQdrantRetrieveEngineRepository(client *qdrant.Client, indexCfg *types.IndexConfig) interfaces.RetrieveEngineRepository {
log := logger.GetLogger(context.Background())
log.Info("[Qdrant] Initializing Qdrant retriever engine repository")
collectionBaseName := os.Getenv(envQdrantCollection)
if collectionBaseName == "" {
log.Warn("[Qdrant] QDRANT_COLLECTION environment variable not set, using default collection name")
collectionBaseName = defaultCollectionName
}
collectionBaseName := types.ResolveCollectionName(indexCfg, envQdrantCollection, defaultCollectionName)
res := &qdrantRepository{
client: client,
collectionBaseName: collectionBaseName,
shardNumber: indexCfg.GetShardNumber(0),
replicationFactor: indexCfg.GetReplicationFactor(0),
}
log.Info("[Qdrant] Successfully initialized repository")
@@ -82,6 +80,8 @@ func (q *qdrantRepository) ensureCollection(ctx context.Context, dimension int)
Size: uint64(dimension),
Distance: qdrant.Distance_Cosine,
}),
ShardNumber: types.OptionalUint32(q.shardNumber),
ReplicationFactor: types.OptionalUint32(q.replicationFactor),
})
if err != nil {
log.Errorf("[Qdrant] Failed to create collection: %v", err)
@@ -9,6 +9,8 @@ import (
type qdrantRepository struct {
client *qdrant.Client
collectionBaseName string
shardNumber int // 0 = use Qdrant server default
replicationFactor int // 0 = use Qdrant server default
// Cache for initialized collections (dimension -> true)
initializedCollections sync.Map
}
@@ -4,7 +4,6 @@ import (
"context"
"fmt"
"maps"
"os"
"slices"
"strings"
"unicode/utf8"
@@ -35,19 +34,19 @@ const (
fieldID = "id"
)
func NewWeaviateRetrieveEngineRepository(client *weaviate.Client) interfaces.RetrieveEngineRepository {
// NewWeaviateRetrieveEngineRepository creates and initializes a new Weaviate repository.
// indexCfg is optional — pass nil to use env var / default values (env path).
func NewWeaviateRetrieveEngineRepository(client *weaviate.Client, indexCfg *types.IndexConfig) interfaces.RetrieveEngineRepository {
log := logger.GetLogger(context.Background())
log.Info("[Weaviate] Initializing Weaviate retriever engine repository")
collectionBaseName := os.Getenv(envWeaviateCollection)
if collectionBaseName == "" {
log.Warn("[Weaviate] WEAVIATE_COLLECTION environment variable not set, using default collection name")
collectionBaseName = defaultCollectionName
}
collectionBaseName := types.ResolveCollectionName(indexCfg, envWeaviateCollection, defaultCollectionName)
res := &weaviateRepository{
client: client,
collectionBaseName: collectionBaseName,
replicationFactor: indexCfg.GetReplicationFactor(0),
desiredShardCount: indexCfg.GetDesiredShardCount(0),
}
log.Info("[Weaviate] Successfully initialized repository")
@@ -137,6 +136,18 @@ func (w *weaviateRepository) ensureCollection(ctx context.Context, dimension int
},
},
}
// Set replication factor if explicitly configured (> 0)
if w.replicationFactor > 0 {
classObj.ReplicationConfig = &models.ReplicationConfig{
Factor: int64(w.replicationFactor),
}
}
// Set shard count if explicitly configured (> 0)
if w.desiredShardCount > 0 {
classObj.ShardingConfig = map[string]interface{}{
"desiredCount": w.desiredShardCount,
}
}
//创建collection
if err = w.client.Schema().ClassCreator().WithClass(&classObj).Do(ctx); err != nil {
log.Errorf("[Weaviate] Failed to create collection: %v", err)
@@ -9,6 +9,8 @@ import (
type weaviateRepository struct {
client *weaviate.Client
collectionBaseName string
replicationFactor int // 0 = use Weaviate server default
desiredShardCount int // 0 = use Weaviate server default
// Cache for initialized collections (dimension -> true)
initializedCollections sync.Map
}
+19 -1
View File
@@ -2,6 +2,7 @@ package service
import (
"context"
"fmt"
"os"
"time"
@@ -44,6 +45,11 @@ func (s *vectorStoreService) CreateStore(ctx context.Context, store *types.Vecto
return err
}
// 2.5. Index config validation (bounds, name characters)
if err := types.ValidateIndexConfig(store.IndexConfig); err != nil {
return err
}
// 3. Duplicate check — DB stores
endpoint := store.ConnectionConfig.GetEndpoint()
indexName := store.IndexConfig.GetIndexNameOrDefault(store.EngineType)
@@ -66,7 +72,19 @@ func (s *vectorStoreService) CreateStore(ctx context.Context, store *types.Vecto
}
}
// 5. Persist
// 5. Auto-detect server version via connection test.
// This is required for engines where the version determines the SDK (e.g., ES v7 vs v8).
// Without it, the wrong SDK may be used causing protocol errors (406, etc.).
version, err := s.TestConnection(ctx, store.EngineType, store.ConnectionConfig)
if err != nil {
return errors.NewBadRequestError(
fmt.Sprintf("connection test failed: %s. Ensure the server is reachable before saving.", err.Error()))
}
if version != "" {
store.ConnectionConfig.Version = version
}
// 6. Persist
logger.Infof(ctx, "Creating vector store: tenant=%d, name=%s, engine=%s",
store.TenantID, secutils.SanitizeForLog(store.Name), store.EngineType)
if err := s.repo.Create(ctx, store); err != nil {
@@ -389,15 +389,14 @@ func TestCreateStore_DifferentEndpointSameIndex_Allowed(t *testing.T) {
repo := &mockVectorStoreRepo{existsByEndpoint: false}
svc := NewVectorStoreService(repo, nil, nil)
// Use postgres with UseDefaultConnection to avoid needing a real ES endpoint.
// The test verifies duplicate-check logic, not connectivity.
store := &types.VectorStore{
TenantID: 1,
Name: "new-store",
EngineType: types.ElasticsearchRetrieverEngineType,
EngineType: types.PostgresRetrieverEngineType,
ConnectionConfig: types.ConnectionConfig{
Addr: "http://es-new:9200",
},
IndexConfig: types.IndexConfig{
IndexName: "shared_index",
UseDefaultConnection: true,
},
}
+5 -5
View File
@@ -771,7 +771,7 @@ func initRetrieveEngineRegistry(db *gorm.DB, cfg *config.Config) (interfaces.Ret
if err != nil {
log.Errorf("Create elasticsearch_v8 client failed: %v", err)
} else {
elasticsearchRepo := elasticsearchRepoV8.NewElasticsearchEngineRepository(client, cfg)
elasticsearchRepo := elasticsearchRepoV8.NewElasticsearchEngineRepository(client, cfg, nil)
if err := registry.Register(
retriever.NewKVHybridRetrieveEngine(
elasticsearchRepo, types.ElasticsearchRetrieverEngineType,
@@ -793,7 +793,7 @@ func initRetrieveEngineRegistry(db *gorm.DB, cfg *config.Config) (interfaces.Ret
if err != nil {
log.Errorf("Create elasticsearch_v7 client failed: %v", err)
} else {
elasticsearchRepo := elasticsearchRepoV7.NewElasticsearchEngineRepository(client, cfg)
elasticsearchRepo := elasticsearchRepoV7.NewElasticsearchEngineRepository(client, cfg, nil)
if err := registry.Register(
retriever.NewKVHybridRetrieveEngine(
elasticsearchRepo, types.ElasticsearchRetrieverEngineType,
@@ -841,7 +841,7 @@ func initRetrieveEngineRegistry(db *gorm.DB, cfg *config.Config) (interfaces.Ret
if err != nil {
log.Errorf("Create qdrant client failed: %v", err)
} else {
qdrantRepository := qdrantRepo.NewQdrantRetrieveEngineRepository(client)
qdrantRepository := qdrantRepo.NewQdrantRetrieveEngineRepository(client, nil)
if err := registry.Register(
retriever.NewKVHybridRetrieveEngine(
qdrantRepository, types.QdrantRetrieverEngineType,
@@ -884,7 +884,7 @@ func initRetrieveEngineRegistry(db *gorm.DB, cfg *config.Config) (interfaces.Ret
if err != nil {
log.Errorf("Create weaviate client failed: %v", err)
} else {
weaviateRepository := weaviateRepo.NewWeaviateRetrieveEngineRepository(weaviateClient)
weaviateRepository := weaviateRepo.NewWeaviateRetrieveEngineRepository(weaviateClient, nil)
if err := registry.Register(
retriever.NewKVHybridRetrieveEngine(
weaviateRepository, types.WeaviateRetrieverEngineType,
@@ -921,7 +921,7 @@ func initRetrieveEngineRegistry(db *gorm.DB, cfg *config.Config) (interfaces.Ret
if err != nil {
log.Errorf("Create milvus client failed: %v", err)
} else {
milvusRepository := milvusRepo.NewMilvusRetrieveEngineRepository(milvusCli)
milvusRepository := milvusRepo.NewMilvusRetrieveEngineRepository(milvusCli, nil)
if err := registry.Register(
retriever.NewKVHybridRetrieveEngine(
milvusRepository, types.MilvusRetrieverEngineType,
+11 -9
View File
@@ -84,9 +84,9 @@ func createElasticsearchEngine(store types.VectorStore, cfg *config.Config) (int
// Version is auto-detected by PR2's TestConnection and saved to connection_config.
// Empty version defaults to v8 (latest SDK).
if isESv7(cc.Version) {
return createElasticsearchV7Engine(cc, cfg)
return createElasticsearchV7Engine(store, cfg)
}
return createElasticsearchV8Engine(cc, cfg)
return createElasticsearchV8Engine(store, cfg)
}
// isESv7 checks if the detected ES version is 7.x.
@@ -94,7 +94,8 @@ func isESv7(version string) bool {
return strings.HasPrefix(version, "7.")
}
func createElasticsearchV8Engine(cc types.ConnectionConfig, cfg *config.Config) (interfaces.RetrieveEngineService, error) {
func createElasticsearchV8Engine(store types.VectorStore, cfg *config.Config) (interfaces.RetrieveEngineService, error) {
cc := store.ConnectionConfig
client, err := elasticsearch.NewTypedClient(elasticsearch.Config{
Addresses: []string{cc.Addr},
Username: cc.Username,
@@ -103,11 +104,12 @@ func createElasticsearchV8Engine(cc types.ConnectionConfig, cfg *config.Config)
if err != nil {
return nil, fmt.Errorf("create elasticsearch v8 client: %w", err)
}
repo := elasticsearchRepoV8.NewElasticsearchEngineRepository(client, cfg)
repo := elasticsearchRepoV8.NewElasticsearchEngineRepository(client, cfg, &store.IndexConfig)
return retriever.NewKVHybridRetrieveEngine(repo, types.ElasticsearchRetrieverEngineType), nil
}
func createElasticsearchV7Engine(cc types.ConnectionConfig, cfg *config.Config) (interfaces.RetrieveEngineService, error) {
func createElasticsearchV7Engine(store types.VectorStore, cfg *config.Config) (interfaces.RetrieveEngineService, error) {
cc := store.ConnectionConfig
client, err := esv7.NewClient(esv7.Config{
Addresses: []string{cc.Addr},
Username: cc.Username,
@@ -116,7 +118,7 @@ func createElasticsearchV7Engine(cc types.ConnectionConfig, cfg *config.Config)
if err != nil {
return nil, fmt.Errorf("create elasticsearch v7 client: %w", err)
}
repo := elasticsearchRepoV7.NewElasticsearchEngineRepository(client, cfg)
repo := elasticsearchRepoV7.NewElasticsearchEngineRepository(client, cfg, &store.IndexConfig)
return retriever.NewKVHybridRetrieveEngine(repo, types.ElasticsearchRetrieverEngineType), nil
}
@@ -136,7 +138,7 @@ func createQdrantEngine(store types.VectorStore) (interfaces.RetrieveEngineServi
if err != nil {
return nil, fmt.Errorf("create qdrant client: %w", err)
}
repo := qdrantRepo.NewQdrantRetrieveEngineRepository(client)
repo := qdrantRepo.NewQdrantRetrieveEngineRepository(client, &store.IndexConfig)
return retriever.NewKVHybridRetrieveEngine(repo, types.QdrantRetrieverEngineType), nil
}
@@ -164,7 +166,7 @@ func createMilvusEngine(ctx context.Context, store types.VectorStore) (interface
if err != nil {
return nil, fmt.Errorf("create milvus client: %w", err)
}
repo := milvusRepo.NewMilvusRetrieveEngineRepository(client)
repo := milvusRepo.NewMilvusRetrieveEngineRepository(client, &store.IndexConfig)
return retriever.NewKVHybridRetrieveEngine(repo, types.MilvusRetrieverEngineType), nil
}
@@ -200,6 +202,6 @@ func createWeaviateEngine(store types.VectorStore) (interfaces.RetrieveEngineSer
if err != nil {
return nil, fmt.Errorf("create weaviate client: %w", err)
}
repo := weaviateRepo.NewWeaviateRetrieveEngineRepository(client)
repo := weaviateRepo.NewWeaviateRetrieveEngineRepository(client, &store.IndexConfig)
return retriever.NewKVHybridRetrieveEngine(repo, types.WeaviateRetrieverEngineType), nil
}
+190 -5
View File
@@ -4,6 +4,8 @@ import (
"database/sql/driver"
"encoding/json"
"fmt"
"os"
"regexp"
"strings"
"time"
@@ -201,11 +203,19 @@ func (c ConnectionConfig) MaskSensitiveFields() ConnectionConfig {
// IndexConfig holds optional index/collection configuration for the vector store.
// If empty, engine-specific defaults are used.
type IndexConfig struct {
// --- Existing fields ---
IndexName string `yaml:"index_name" json:"index_name,omitempty"` // ES, OpenSearch
NumberOfShards int `yaml:"number_of_shards" json:"number_of_shards,omitempty"` // ES, OpenSearch
NumberOfReplicas int `yaml:"number_of_replicas" json:"number_of_replicas,omitempty"` // ES, OpenSearch
CollectionPrefix string `yaml:"collection_prefix" json:"collection_prefix,omitempty"` // Qdrant
CollectionPrefix string `yaml:"collection_prefix" json:"collection_prefix,omitempty"` // Qdrant, Weaviate
CollectionName string `yaml:"collection_name" json:"collection_name,omitempty"` // Milvus
// --- Scalability fields ---
ShardNumber int `yaml:"shard_number" json:"shard_number,omitempty"` // Qdrant: number of shards per collection
ReplicationFactor int `yaml:"replication_factor" json:"replication_factor,omitempty"` // Qdrant, Weaviate: number of replicas
ShardsNum int `yaml:"shards_num" json:"shards_num,omitempty"` // Milvus: number of shards per collection (CreateCollection)
ReplicaNumber int `yaml:"replica_number" json:"replica_number,omitempty"` // Milvus: in-memory replica count (LoadCollection)
DesiredShardCount int `yaml:"desired_shard_count" json:"desired_shard_count,omitempty"` // Weaviate: number of shards per collection
}
// Value implements the driver.Valuer interface.
@@ -248,12 +258,181 @@ func (c IndexConfig) GetIndexNameOrDefault(engineType RetrieverEngineType) strin
if c.CollectionPrefix != "" {
return c.CollectionPrefix
}
return "WeKnora"
return "Weknora_embeddings"
default:
return c.IndexName
}
}
// ---------------------------------------------------------------------------
// IndexConfig — getter helpers (pointer receiver for nil safety)
// ---------------------------------------------------------------------------
// GetNumberOfShards returns the configured number_of_shards, or def if unset/zero.
func (c *IndexConfig) GetNumberOfShards(def int) int {
if c != nil && c.NumberOfShards > 0 {
return c.NumberOfShards
}
return def
}
// GetNumberOfReplicas returns the configured number_of_replicas, or def if unset/zero.
// Note: 0 replicas cannot be distinguished from "not set" because the int field with
// json:"omitempty" omits zero values. If zero-replica support is needed in the future,
// change the field type to *int. Currently 0 is treated as "use server default".
func (c *IndexConfig) GetNumberOfReplicas(def int) int {
if c != nil && c.NumberOfReplicas > 0 {
return c.NumberOfReplicas
}
return def
}
// GetShardNumber returns the configured shard_number (Qdrant), or def if unset/zero.
func (c *IndexConfig) GetShardNumber(def int) int {
if c != nil && c.ShardNumber > 0 {
return c.ShardNumber
}
return def
}
// GetReplicationFactor returns the configured replication_factor (Qdrant, Weaviate), or def if unset/zero.
func (c *IndexConfig) GetReplicationFactor(def int) int {
if c != nil && c.ReplicationFactor > 0 {
return c.ReplicationFactor
}
return def
}
// GetShardsNum returns the configured shards_num (Milvus), or def if unset/zero.
func (c *IndexConfig) GetShardsNum(def int) int {
if c != nil && c.ShardsNum > 0 {
return c.ShardsNum
}
return def
}
// GetReplicaNumber returns the configured replica_number (Milvus in-memory replicas), or def if unset/zero.
// Milvus replicas are set at LoadCollection time, not CreateCollection.
// They control how many query nodes hold the data in memory for read HA/throughput.
func (c *IndexConfig) GetReplicaNumber(def int) int {
if c != nil && c.ReplicaNumber > 0 {
return c.ReplicaNumber
}
return def
}
// GetDesiredShardCount returns the configured desired_shard_count (Weaviate), or def if unset/zero.
func (c *IndexConfig) GetDesiredShardCount(def int) int {
if c != nil && c.DesiredShardCount > 0 {
return c.DesiredShardCount
}
return def
}
// ---------------------------------------------------------------------------
// IndexConfig — resolve helpers (for Repository layer, with env var fallback)
// ---------------------------------------------------------------------------
// ResolveIndexName returns the index name from IndexConfig, falling back to env var and then default.
// Used by Repository constructors. For service-layer duplicate checking, use GetIndexNameOrDefault instead.
func ResolveIndexName(ic *IndexConfig, envKey, defaultVal string) string {
if ic != nil && ic.IndexName != "" {
return ic.IndexName
}
if v := os.Getenv(envKey); v != "" {
return v
}
return defaultVal
}
// ResolveCollectionName returns the collection name from IndexConfig, falling back to env var and then default.
// Priority: CollectionPrefix > CollectionName > env var > defaultVal.
// CollectionPrefix is checked first because Qdrant/Weaviate use it as the base name.
// CollectionName (Milvus) is checked second. If both are set, CollectionPrefix wins —
// this is safe because each VectorStore has a single engine type, so only one field is relevant.
func ResolveCollectionName(ic *IndexConfig, envKey, defaultVal string) string {
if ic != nil {
if ic.CollectionPrefix != "" {
return ic.CollectionPrefix
}
if ic.CollectionName != "" {
return ic.CollectionName
}
}
if v := os.Getenv(envKey); v != "" {
return v
}
return defaultVal
}
// OptionalUint32 converts int to *uint32 for Qdrant SDK.
// Returns nil for values <= 0, which tells Qdrant to use its server default.
func OptionalUint32(v int) *uint32 {
if v <= 0 {
return nil
}
u := uint32(v)
return &u
}
// ---------------------------------------------------------------------------
// IndexConfig — validation
// ---------------------------------------------------------------------------
const (
// maxShards is the upper bound for shard-related configuration values.
maxShards = 64
// maxReplicas is the upper bound for replication-related configuration values.
maxReplicas = 10
)
// validIndexNamePattern restricts index/collection names to safe characters.
// Must start with a letter, followed by alphanumeric, underscore, or hyphen. Max 128 chars.
var validIndexNamePattern = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9_-]{0,127}$`)
// ValidateIndexConfig checks IndexConfig fields for safe values.
// Call this from the service layer before persisting a VectorStore.
func ValidateIndexConfig(ic IndexConfig) error {
// Validate string fields (index/collection names)
if ic.IndexName != "" && !validIndexNamePattern.MatchString(ic.IndexName) {
return errors.NewValidationError(
"index_name must start with a letter and contain only alphanumeric, underscore, or hyphen characters (max 128)")
}
if ic.CollectionPrefix != "" && !validIndexNamePattern.MatchString(ic.CollectionPrefix) {
return errors.NewValidationError(
"collection_prefix must start with a letter and contain only alphanumeric, underscore, or hyphen characters (max 128)")
}
if ic.CollectionName != "" && !validIndexNamePattern.MatchString(ic.CollectionName) {
return errors.NewValidationError(
"collection_name must start with a letter and contain only alphanumeric, underscore, or hyphen characters (max 128)")
}
// Validate numeric fields (shards/replicas) — must be within safe bounds
if ic.NumberOfShards < 0 || ic.NumberOfShards > maxShards {
return errors.NewValidationError(fmt.Sprintf("number_of_shards must be between 0 and %d", maxShards))
}
if ic.NumberOfReplicas < 0 || ic.NumberOfReplicas > maxReplicas {
return errors.NewValidationError(fmt.Sprintf("number_of_replicas must be between 0 and %d", maxReplicas))
}
if ic.ShardNumber < 0 || ic.ShardNumber > maxShards {
return errors.NewValidationError(fmt.Sprintf("shard_number must be between 0 and %d", maxShards))
}
if ic.ReplicationFactor < 0 || ic.ReplicationFactor > maxReplicas {
return errors.NewValidationError(fmt.Sprintf("replication_factor must be between 0 and %d", maxReplicas))
}
if ic.ShardsNum < 0 || ic.ShardsNum > maxShards {
return errors.NewValidationError(fmt.Sprintf("shards_num must be between 0 and %d", maxShards))
}
if ic.ReplicaNumber < 0 || ic.ReplicaNumber > maxReplicas {
return errors.NewValidationError(fmt.Sprintf("replica_number must be between 0 and %d", maxReplicas))
}
if ic.DesiredShardCount < 0 || ic.DesiredShardCount > maxShards {
return errors.NewValidationError(fmt.Sprintf("desired_shard_count must be between 0 and %d", maxShards))
}
return nil
}
// ---------------------------------------------------------------------------
// VectorStoreResponse — API response DTO
// ---------------------------------------------------------------------------
@@ -339,7 +518,9 @@ func GetVectorStoreTypes() []VectorStoreTypeInfo {
{Name: "use_tls", Type: "boolean", Required: false, Default: false},
},
IndexFields: []VectorStoreFieldInfo{
{Name: "collection_prefix", Type: "string", Required: false, Default: "weknora_embeddings"},
{Name: "collection_prefix", Type: "string", Required: false, Default: "weknora_embeddings", Description: "Collection Prefix"},
{Name: "shard_number", Type: "number", Required: false, Default: 1, Description: "Shard Number"},
{Name: "replication_factor", Type: "number", Required: false, Default: 1, Description: "Replication Factor"},
},
},
{
@@ -351,7 +532,9 @@ func GetVectorStoreTypes() []VectorStoreTypeInfo {
{Name: "password", Type: "string", Required: false, Sensitive: true},
},
IndexFields: []VectorStoreFieldInfo{
{Name: "collection_name", Type: "string", Required: false, Default: "weknora_embeddings"},
{Name: "collection_name", Type: "string", Required: false, Default: "weknora_embeddings", Description: "Collection Name"},
{Name: "shards_num", Type: "number", Required: false, Default: 1, Description: "Shards (write parallelism)"},
{Name: "replica_number", Type: "number", Required: false, Default: 1, Description: "In-memory Replicas (read HA)"},
},
},
{
@@ -364,7 +547,9 @@ func GetVectorStoreTypes() []VectorStoreTypeInfo {
{Name: "api_key", Type: "string", Required: false, Sensitive: true},
},
IndexFields: []VectorStoreFieldInfo{
{Name: "collection_prefix", Type: "string", Required: false, Default: "WeKnora"},
{Name: "collection_prefix", Type: "string", Required: false, Default: "Weknora_embeddings", Description: "Collection Prefix"},
{Name: "desired_shard_count", Type: "number", Required: false, Default: 1, Description: "Shard Count"},
{Name: "replication_factor", Type: "number", Required: false, Default: 1, Description: "Replication Factor"},
},
},
{
+299 -1
View File
@@ -622,7 +622,7 @@ func TestIndexConfig_GetIndexNameOrDefault(t *testing.T) {
name: "weaviate default",
config: IndexConfig{},
engineType: WeaviateRetrieverEngineType,
expected: "WeKnora",
expected: "Weknora_embeddings",
},
// Postgres (no index config)
{
@@ -645,3 +645,301 @@ func TestIndexConfig_GetIndexNameOrDefault(t *testing.T) {
})
}
}
// ---------------------------------------------------------------------------
// IndexConfig — getter helpers
// ---------------------------------------------------------------------------
func TestIndexConfig_GetterHelpers(t *testing.T) {
t.Run("nil receiver returns default", func(t *testing.T) {
var ic *IndexConfig
assert.Equal(t, 5, ic.GetNumberOfShards(5))
assert.Equal(t, -1, ic.GetNumberOfReplicas(-1))
assert.Equal(t, 0, ic.GetShardNumber(0))
assert.Equal(t, 0, ic.GetReplicationFactor(0))
assert.Equal(t, 1, ic.GetShardsNum(1))
assert.Equal(t, 0, ic.GetReplicaNumber(0))
assert.Equal(t, 0, ic.GetDesiredShardCount(0))
})
t.Run("zero value returns default", func(t *testing.T) {
ic := &IndexConfig{}
assert.Equal(t, 5, ic.GetNumberOfShards(5))
assert.Equal(t, -1, ic.GetNumberOfReplicas(-1))
assert.Equal(t, 0, ic.GetShardNumber(0))
assert.Equal(t, 0, ic.GetReplicationFactor(0))
assert.Equal(t, 1, ic.GetShardsNum(1))
assert.Equal(t, 0, ic.GetReplicaNumber(0))
assert.Equal(t, 0, ic.GetDesiredShardCount(0))
})
t.Run("positive value overrides default", func(t *testing.T) {
ic := &IndexConfig{
NumberOfShards: 3,
NumberOfReplicas: 2,
ShardNumber: 4,
ReplicationFactor: 3,
ShardsNum: 5,
ReplicaNumber: 2,
DesiredShardCount: 3,
}
assert.Equal(t, 3, ic.GetNumberOfShards(1))
assert.Equal(t, 2, ic.GetNumberOfReplicas(-1))
assert.Equal(t, 4, ic.GetShardNumber(0))
assert.Equal(t, 3, ic.GetReplicationFactor(0))
assert.Equal(t, 5, ic.GetShardsNum(1))
assert.Equal(t, 2, ic.GetReplicaNumber(0))
assert.Equal(t, 3, ic.GetDesiredShardCount(0))
})
t.Run("negative value returns default (treated as unset)", func(t *testing.T) {
ic := &IndexConfig{
NumberOfShards: -1,
NumberOfReplicas: -1,
ShardNumber: -5,
ReplicationFactor: -1,
ShardsNum: -1,
ReplicaNumber: -1,
DesiredShardCount: -1,
}
assert.Equal(t, 1, ic.GetNumberOfShards(1))
assert.Equal(t, -1, ic.GetNumberOfReplicas(-1))
assert.Equal(t, 0, ic.GetShardNumber(0))
assert.Equal(t, 0, ic.GetReplicationFactor(0))
assert.Equal(t, 1, ic.GetShardsNum(1))
assert.Equal(t, 0, ic.GetReplicaNumber(0))
assert.Equal(t, 0, ic.GetDesiredShardCount(0))
})
}
// ---------------------------------------------------------------------------
// IndexConfig — resolve helpers
// ---------------------------------------------------------------------------
func TestResolveIndexName(t *testing.T) {
t.Run("nil IndexConfig falls back to env var", func(t *testing.T) {
t.Setenv("ELASTICSEARCH_INDEX", "env_index")
assert.Equal(t, "env_index", ResolveIndexName(nil, "ELASTICSEARCH_INDEX", "default"))
})
t.Run("nil IndexConfig falls back to default when env empty", func(t *testing.T) {
t.Setenv("ELASTICSEARCH_INDEX", "")
assert.Equal(t, "xwrag_default", ResolveIndexName(nil, "ELASTICSEARCH_INDEX", "xwrag_default"))
})
t.Run("IndexConfig value takes precedence over env var", func(t *testing.T) {
t.Setenv("ELASTICSEARCH_INDEX", "env_index")
ic := &IndexConfig{IndexName: "custom_index"}
assert.Equal(t, "custom_index", ResolveIndexName(ic, "ELASTICSEARCH_INDEX", "default"))
})
t.Run("empty IndexConfig.IndexName falls back to env var", func(t *testing.T) {
t.Setenv("ELASTICSEARCH_INDEX", "env_index")
ic := &IndexConfig{}
assert.Equal(t, "env_index", ResolveIndexName(ic, "ELASTICSEARCH_INDEX", "default"))
})
}
func TestResolveCollectionName(t *testing.T) {
t.Run("nil IndexConfig falls back to env var", func(t *testing.T) {
t.Setenv("QDRANT_COLLECTION", "env_collection")
assert.Equal(t, "env_collection", ResolveCollectionName(nil, "QDRANT_COLLECTION", "default"))
})
t.Run("CollectionPrefix takes precedence over CollectionName", func(t *testing.T) {
ic := &IndexConfig{CollectionPrefix: "prefix_name", CollectionName: "full_name"}
assert.Equal(t, "prefix_name", ResolveCollectionName(ic, "QDRANT_COLLECTION", "default"))
})
t.Run("CollectionName used when CollectionPrefix empty", func(t *testing.T) {
ic := &IndexConfig{CollectionName: "full_name"}
assert.Equal(t, "full_name", ResolveCollectionName(ic, "MILVUS_COLLECTION", "default"))
})
t.Run("empty IndexConfig falls back to default", func(t *testing.T) {
t.Setenv("QDRANT_COLLECTION", "")
ic := &IndexConfig{}
assert.Equal(t, "weknora_embeddings", ResolveCollectionName(ic, "QDRANT_COLLECTION", "weknora_embeddings"))
})
}
// ---------------------------------------------------------------------------
// OptionalUint32
// ---------------------------------------------------------------------------
func TestOptionalUint32(t *testing.T) {
t.Run("zero returns nil", func(t *testing.T) {
assert.Nil(t, OptionalUint32(0))
})
t.Run("negative returns nil", func(t *testing.T) {
assert.Nil(t, OptionalUint32(-1))
assert.Nil(t, OptionalUint32(-100))
})
t.Run("positive returns pointer to uint32", func(t *testing.T) {
result := OptionalUint32(3)
require.NotNil(t, result)
assert.Equal(t, uint32(3), *result)
})
t.Run("large positive value", func(t *testing.T) {
result := OptionalUint32(64)
require.NotNil(t, result)
assert.Equal(t, uint32(64), *result)
})
}
// ---------------------------------------------------------------------------
// ValidateIndexConfig
// ---------------------------------------------------------------------------
func TestValidateIndexConfig(t *testing.T) {
t.Run("empty config is valid", func(t *testing.T) {
assert.NoError(t, ValidateIndexConfig(IndexConfig{}))
})
t.Run("valid config with all fields", func(t *testing.T) {
ic := IndexConfig{
IndexName: "my_index",
NumberOfShards: 3,
NumberOfReplicas: 1,
CollectionPrefix: "my_collection",
ShardNumber: 4,
ReplicationFactor: 2,
ShardsNum: 2,
ReplicaNumber: 3,
DesiredShardCount: 2,
}
assert.NoError(t, ValidateIndexConfig(ic))
})
// --- Name validation ---
t.Run("index_name with special chars rejected", func(t *testing.T) {
ic := IndexConfig{IndexName: "my index*"}
err := ValidateIndexConfig(ic)
require.Error(t, err)
assert.Contains(t, err.Error(), "index_name")
})
t.Run("index_name starting with number rejected", func(t *testing.T) {
ic := IndexConfig{IndexName: "123abc"}
err := ValidateIndexConfig(ic)
require.Error(t, err)
})
t.Run("collection_prefix with slash rejected", func(t *testing.T) {
ic := IndexConfig{CollectionPrefix: "path/to/collection"}
err := ValidateIndexConfig(ic)
require.Error(t, err)
assert.Contains(t, err.Error(), "collection_prefix")
})
t.Run("collection_name with dot rejected", func(t *testing.T) {
ic := IndexConfig{CollectionName: "my.collection"}
err := ValidateIndexConfig(ic)
require.Error(t, err)
assert.Contains(t, err.Error(), "collection_name")
})
t.Run("valid names with underscore and hyphen", func(t *testing.T) {
ic := IndexConfig{
IndexName: "my_index-v2",
CollectionPrefix: "Weknora_embeddings",
CollectionName: "custom-collection-name",
}
assert.NoError(t, ValidateIndexConfig(ic))
})
// --- Numeric bounds ---
t.Run("number_of_shards exceeds max", func(t *testing.T) {
ic := IndexConfig{NumberOfShards: 100}
err := ValidateIndexConfig(ic)
require.Error(t, err)
assert.Contains(t, err.Error(), "number_of_shards")
})
t.Run("negative number_of_shards rejected", func(t *testing.T) {
ic := IndexConfig{NumberOfShards: -1}
err := ValidateIndexConfig(ic)
require.Error(t, err)
assert.Contains(t, err.Error(), "number_of_shards")
})
t.Run("replication_factor exceeds max", func(t *testing.T) {
ic := IndexConfig{ReplicationFactor: 50}
err := ValidateIndexConfig(ic)
require.Error(t, err)
assert.Contains(t, err.Error(), "replication_factor")
})
t.Run("shard_number at max boundary is valid", func(t *testing.T) {
ic := IndexConfig{ShardNumber: 64}
assert.NoError(t, ValidateIndexConfig(ic))
})
t.Run("replication_factor at max boundary is valid", func(t *testing.T) {
ic := IndexConfig{ReplicationFactor: 10}
assert.NoError(t, ValidateIndexConfig(ic))
})
t.Run("shards_num exceeds max", func(t *testing.T) {
ic := IndexConfig{ShardsNum: 999}
err := ValidateIndexConfig(ic)
require.Error(t, err)
assert.Contains(t, err.Error(), "shards_num")
})
t.Run("replica_number exceeds max", func(t *testing.T) {
ic := IndexConfig{ReplicaNumber: 50}
err := ValidateIndexConfig(ic)
require.Error(t, err)
assert.Contains(t, err.Error(), "replica_number")
})
t.Run("desired_shard_count exceeds max", func(t *testing.T) {
ic := IndexConfig{DesiredShardCount: 100}
err := ValidateIndexConfig(ic)
require.Error(t, err)
assert.Contains(t, err.Error(), "desired_shard_count")
})
}
// ---------------------------------------------------------------------------
// IndexConfig — scalability fields round-trip
// ---------------------------------------------------------------------------
func TestIndexConfig_ScalabilityFieldsRoundTrip(t *testing.T) {
t.Run("scalability fields serialize and deserialize", func(t *testing.T) {
original := IndexConfig{
IndexName: "my_index",
NumberOfShards: 3,
NumberOfReplicas: 1,
CollectionPrefix: "my_prefix",
ShardNumber: 4,
ReplicationFactor: 2,
ShardsNum: 5,
ReplicaNumber: 3,
DesiredShardCount: 2,
}
raw, err := original.Value()
require.NoError(t, err)
var scanned IndexConfig
require.NoError(t, scanned.Scan(raw.([]byte)))
assert.Equal(t, original, scanned)
})
t.Run("scalability fields omitted when zero", func(t *testing.T) {
raw, err := IndexConfig{IndexName: "test"}.Value()
require.NoError(t, err)
var parsed map[string]interface{}
require.NoError(t, json.Unmarshal(raw.([]byte), &parsed))
assert.NotContains(t, parsed, "shard_number")
assert.NotContains(t, parsed, "replication_factor")
assert.NotContains(t, parsed, "shards_num")
assert.NotContains(t, parsed, "replica_number")
assert.NotContains(t, parsed, "desired_shard_count")
})
}