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
}