feat: add Tencent VectorDB retriever backend
This commit is contained in:
@@ -0,0 +1,542 @@
|
||||
package tencentvectordb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"maps"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/tencent/vectordatabase-sdk-go/tcvectordb"
|
||||
)
|
||||
|
||||
// NewTencentVectorDBRetrieveEngineRepository creates a Tencent VectorDB-backed retrieve repository.
|
||||
func NewTencentVectorDBRetrieveEngineRepository(
|
||||
client *tcvectordb.RpcClient,
|
||||
databaseName string,
|
||||
indexCfg *types.IndexConfig,
|
||||
) interfaces.RetrieveEngineRepository {
|
||||
if databaseName == "" {
|
||||
databaseName = os.Getenv(envTencentVectorDBDatabase)
|
||||
}
|
||||
if databaseName == "" {
|
||||
databaseName = defaultDatabaseName
|
||||
}
|
||||
|
||||
collectionBaseName := types.ResolveCollectionName(indexCfg, envTencentVectorDBCollection, defaultCollectionName)
|
||||
return &repository{
|
||||
client: client,
|
||||
databaseName: databaseName,
|
||||
collectionBaseName: collectionBaseName,
|
||||
shardsNum: defaultIfZero(indexCfg.GetShardsNum(1), 1),
|
||||
replicasNum: defaultIfZero(indexCfg.GetReplicaNumber(1), 1),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repository) EngineType() types.RetrieverEngineType {
|
||||
return types.TencentVectorDBRetrieverEngineType
|
||||
}
|
||||
|
||||
func (r *repository) Support() []types.RetrieverType {
|
||||
return []types.RetrieverType{types.VectorRetrieverType}
|
||||
}
|
||||
|
||||
func (r *repository) Save(ctx context.Context, indexInfo *types.IndexInfo, params map[string]any) error {
|
||||
return r.BatchSave(ctx, []*types.IndexInfo{indexInfo}, params)
|
||||
}
|
||||
|
||||
func (r *repository) BatchSave(ctx context.Context, indexInfoList []*types.IndexInfo, params map[string]any) error {
|
||||
log := logger.GetLogger(ctx)
|
||||
if len(indexInfoList) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
docsByDimension := make(map[int][]tcvectordb.Document)
|
||||
for _, indexInfo := range indexInfoList {
|
||||
embedding := toVectorEmbedding(indexInfo, params)
|
||||
if len(embedding.Embedding) == 0 {
|
||||
log.Warnf("[TencentVectorDB] skip empty embedding for chunk_id=%s", indexInfo.ChunkID)
|
||||
continue
|
||||
}
|
||||
dim := len(embedding.Embedding)
|
||||
docsByDimension[dim] = append(docsByDimension[dim], toDocument(embedding))
|
||||
}
|
||||
if len(docsByDimension) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
buildIndex := true
|
||||
for dim, docs := range docsByDimension {
|
||||
if err := r.ensureCollection(ctx, dim); err != nil {
|
||||
return err
|
||||
}
|
||||
collectionName := r.collectionName(dim)
|
||||
_, err := r.client.Database(r.databaseName).Collection(collectionName).Upsert(
|
||||
ctx,
|
||||
docs,
|
||||
&tcvectordb.UpsertDocumentParams{BuildIndex: &buildIndex},
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("tencent vectordb batch save %s: %w", collectionName, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *repository) EstimateStorageSize(ctx context.Context, indexInfoList []*types.IndexInfo, params map[string]any) int64 {
|
||||
var total int64
|
||||
for _, indexInfo := range indexInfoList {
|
||||
embedding := toVectorEmbedding(indexInfo, params)
|
||||
total += int64(len(embedding.Content))
|
||||
total += int64(len(embedding.Embedding) * 4)
|
||||
total += int64(len(embedding.SourceID) + len(embedding.ChunkID) + len(embedding.KnowledgeID) + len(embedding.KnowledgeBaseID) + 256)
|
||||
}
|
||||
logger.GetLogger(ctx).Infof("[TencentVectorDB] estimated storage size for %d indices: %d bytes", len(indexInfoList), total)
|
||||
return total
|
||||
}
|
||||
|
||||
func (r *repository) DeleteByChunkIDList(ctx context.Context, chunkIDList []string, dimension int, knowledgeType string) error {
|
||||
return r.deleteByFilter(ctx, dimension, tcvectordb.In(fieldChunkID, chunkIDList))
|
||||
}
|
||||
|
||||
func (r *repository) DeleteBySourceIDList(ctx context.Context, sourceIDList []string, dimension int, knowledgeType string) error {
|
||||
return r.deleteByFilter(ctx, dimension, tcvectordb.In(fieldSourceID, sourceIDList))
|
||||
}
|
||||
|
||||
func (r *repository) DeleteByKnowledgeIDList(ctx context.Context, knowledgeIDList []string, dimension int, knowledgeType string) error {
|
||||
return r.deleteByFilter(ctx, dimension, tcvectordb.In(fieldKnowledgeID, knowledgeIDList))
|
||||
}
|
||||
|
||||
func (r *repository) CopyIndices(
|
||||
ctx context.Context,
|
||||
sourceKnowledgeBaseID string,
|
||||
sourceToTargetKBIDMap map[string]string,
|
||||
sourceToTargetChunkIDMap map[string]string,
|
||||
targetKnowledgeBaseID string,
|
||||
dimension int,
|
||||
knowledgeType string,
|
||||
) error {
|
||||
if len(sourceToTargetChunkIDMap) == 0 {
|
||||
return nil
|
||||
}
|
||||
collectionName := r.collectionName(dimension)
|
||||
ids := slices.Collect(maps.Keys(sourceToTargetChunkIDMap))
|
||||
query, err := r.client.Database(r.databaseName).Collection(collectionName).Query(
|
||||
ctx,
|
||||
nil,
|
||||
&tcvectordb.QueryDocumentParams{
|
||||
Filter: tcvectordb.NewFilter(tcvectordb.In(fieldChunkID, ids)),
|
||||
RetrieveVector: true,
|
||||
OutputFields: outputFields(),
|
||||
Limit: int64(len(ids)),
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("tencent vectordb query source indices: %w", err)
|
||||
}
|
||||
|
||||
docs := make([]tcvectordb.Document, 0, len(query.Documents))
|
||||
for _, doc := range query.Documents {
|
||||
embedding := fromDocument(doc)
|
||||
targetChunkID := sourceToTargetChunkIDMap[embedding.ChunkID]
|
||||
if targetChunkID == "" {
|
||||
continue
|
||||
}
|
||||
embedding.ID = targetChunkID
|
||||
embedding.ChunkID = targetChunkID
|
||||
embedding.KnowledgeBaseID = targetKnowledgeBaseID
|
||||
if targetKBID := sourceToTargetKBIDMap[embedding.KnowledgeID]; targetKBID != "" {
|
||||
embedding.KnowledgeID = targetKBID
|
||||
}
|
||||
docs = append(docs, toDocument(embedding))
|
||||
}
|
||||
if len(docs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
buildIndex := true
|
||||
_, err = r.client.Database(r.databaseName).Collection(collectionName).Upsert(
|
||||
ctx,
|
||||
docs,
|
||||
&tcvectordb.UpsertDocumentParams{BuildIndex: &buildIndex},
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("tencent vectordb copy indices: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *repository) BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error {
|
||||
if len(chunkStatusMap) == 0 {
|
||||
return nil
|
||||
}
|
||||
grouped := make(map[bool][]string)
|
||||
for chunkID, enabled := range chunkStatusMap {
|
||||
grouped[enabled] = append(grouped[enabled], chunkID)
|
||||
}
|
||||
for enabled, chunkIDs := range grouped {
|
||||
if err := r.updateChunkFields(ctx, chunkIDs, map[string]tcvectordb.Field{fieldIsEnabled: {Val: boolToUint64(enabled)}}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *repository) BatchUpdateChunkTagID(ctx context.Context, chunkTagMap map[string]string) error {
|
||||
if len(chunkTagMap) == 0 {
|
||||
return nil
|
||||
}
|
||||
grouped := make(map[string][]string)
|
||||
for chunkID, tagID := range chunkTagMap {
|
||||
grouped[tagID] = append(grouped[tagID], chunkID)
|
||||
}
|
||||
for tagID, chunkIDs := range grouped {
|
||||
if err := r.updateChunkFields(ctx, chunkIDs, map[string]tcvectordb.Field{fieldTagID: {Val: tagID}}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *repository) Retrieve(ctx context.Context, params types.RetrieveParams) ([]*types.RetrieveResult, error) {
|
||||
switch params.RetrieverType {
|
||||
case types.VectorRetrieverType:
|
||||
return r.VectorRetrieve(ctx, params)
|
||||
case types.KeywordsRetrieverType:
|
||||
return nil, fmt.Errorf("tencent vectordb keyword retrieval is not supported")
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid retriever type: %s", params.RetrieverType)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *repository) VectorRetrieve(ctx context.Context, params types.RetrieveParams) ([]*types.RetrieveResult, error) {
|
||||
dimension := len(params.Embedding)
|
||||
if dimension == 0 {
|
||||
return r.retrieveResult(nil, types.VectorRetrieverType), nil
|
||||
}
|
||||
|
||||
collectionName := r.collectionName(dimension)
|
||||
exists, err := r.client.Database(r.databaseName).ExistsCollection(ctx, collectionName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tencent vectordb check collection %s: %w", collectionName, err)
|
||||
}
|
||||
if !exists {
|
||||
return r.retrieveResult(nil, types.VectorRetrieverType), nil
|
||||
}
|
||||
|
||||
limit := int64(params.TopK)
|
||||
if limit <= 0 {
|
||||
limit = 10
|
||||
}
|
||||
searchParams := &tcvectordb.SearchDocumentParams{
|
||||
Filter: r.baseFilter(params),
|
||||
Params: &tcvectordb.SearchDocParams{Ef: 100},
|
||||
RetrieveVector: false,
|
||||
OutputFields: outputFields(),
|
||||
Limit: limit,
|
||||
}
|
||||
if params.Threshold > 0 {
|
||||
radius := float32(params.Threshold)
|
||||
searchParams.Radius = &radius
|
||||
}
|
||||
|
||||
search, err := r.client.Database(r.databaseName).Collection(collectionName).Search(ctx, [][]float32{params.Embedding}, searchParams)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tencent vectordb vector search %s: %w", collectionName, err)
|
||||
}
|
||||
if len(search.Documents) == 0 {
|
||||
return r.retrieveResult(nil, types.VectorRetrieverType), nil
|
||||
}
|
||||
|
||||
results := make([]*types.IndexWithScore, 0, len(search.Documents[0]))
|
||||
for _, doc := range search.Documents[0] {
|
||||
embedding := fromDocument(doc)
|
||||
results = append(results, toIndexWithScore(embedding, types.MatchTypeEmbedding))
|
||||
}
|
||||
return r.retrieveResult(results, types.VectorRetrieverType), nil
|
||||
}
|
||||
|
||||
func (r *repository) ensureCollection(ctx context.Context, dimension int) error {
|
||||
if _, ok := r.initialized.Load(dimension); ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
if _, err := r.client.CreateDatabaseIfNotExists(ctx, r.databaseName); err != nil {
|
||||
return fmt.Errorf("tencent vectordb ensure database %s: %w", r.databaseName, err)
|
||||
}
|
||||
|
||||
collectionName := r.collectionName(dimension)
|
||||
exists, err := r.client.Database(r.databaseName).ExistsCollection(ctx, collectionName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("tencent vectordb check collection %s: %w", collectionName, err)
|
||||
}
|
||||
if exists {
|
||||
r.initialized.Store(dimension, true)
|
||||
return nil
|
||||
}
|
||||
|
||||
indexes := tcvectordb.Indexes{
|
||||
VectorIndex: []tcvectordb.VectorIndex{
|
||||
{
|
||||
FilterIndex: tcvectordb.FilterIndex{
|
||||
FieldName: fieldVector,
|
||||
FieldType: tcvectordb.Vector,
|
||||
IndexType: tcvectordb.HNSW,
|
||||
},
|
||||
Dimension: uint32(dimension),
|
||||
MetricType: tcvectordb.COSINE,
|
||||
Params: &tcvectordb.HNSWParam{
|
||||
M: 16,
|
||||
EfConstruction: 200,
|
||||
},
|
||||
},
|
||||
},
|
||||
FilterIndex: []tcvectordb.FilterIndex{
|
||||
{FieldName: fieldID, FieldType: tcvectordb.String, IndexType: tcvectordb.PRIMARY},
|
||||
{FieldName: fieldContent, FieldType: tcvectordb.String, IndexType: tcvectordb.FILTER},
|
||||
{FieldName: fieldSourceID, FieldType: tcvectordb.String, IndexType: tcvectordb.FILTER},
|
||||
{FieldName: fieldSourceType, FieldType: tcvectordb.Uint64, IndexType: tcvectordb.FILTER},
|
||||
{FieldName: fieldChunkID, FieldType: tcvectordb.String, IndexType: tcvectordb.FILTER},
|
||||
{FieldName: fieldKnowledgeID, FieldType: tcvectordb.String, IndexType: tcvectordb.FILTER},
|
||||
{FieldName: fieldKnowledgeBaseID, FieldType: tcvectordb.String, IndexType: tcvectordb.FILTER},
|
||||
{FieldName: fieldTagID, FieldType: tcvectordb.String, IndexType: tcvectordb.FILTER},
|
||||
{FieldName: fieldIsEnabled, FieldType: tcvectordb.Uint64, IndexType: tcvectordb.FILTER},
|
||||
},
|
||||
}
|
||||
_, err = r.client.Database(r.databaseName).CreateCollection(
|
||||
ctx,
|
||||
collectionName,
|
||||
uint32(r.shardsNum),
|
||||
uint32(r.replicasNum),
|
||||
fmt.Sprintf("WeKnora embeddings collection with dimension %d", dimension),
|
||||
indexes,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("tencent vectordb create collection %s: %w", collectionName, err)
|
||||
}
|
||||
|
||||
r.initialized.Store(dimension, true)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *repository) deleteByFilter(ctx context.Context, dimension int, cond string) error {
|
||||
if cond == "" {
|
||||
return nil
|
||||
}
|
||||
collectionName := r.collectionName(dimension)
|
||||
_, err := r.client.Database(r.databaseName).Collection(collectionName).Delete(ctx, tcvectordb.DeleteDocumentParams{
|
||||
Filter: tcvectordb.NewFilter(cond),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("tencent vectordb delete from %s: %w", collectionName, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *repository) updateChunkFields(ctx context.Context, chunkIDs []string, fields map[string]tcvectordb.Field) error {
|
||||
collections, err := r.client.Database(r.databaseName).ListCollection(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("tencent vectordb list collections: %w", err)
|
||||
}
|
||||
|
||||
for _, collection := range collections.Collections {
|
||||
if !strings.HasPrefix(collection.CollectionName, r.collectionBaseName+"_") {
|
||||
continue
|
||||
}
|
||||
_, err := r.client.Database(r.databaseName).Collection(collection.CollectionName).Update(ctx, tcvectordb.UpdateDocumentParams{
|
||||
QueryFilter: tcvectordb.NewFilter(tcvectordb.In(fieldChunkID, chunkIDs)),
|
||||
UpdateFields: fields,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("tencent vectordb update chunks in %s: %w", collection.CollectionName, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *repository) collectionName(dimension int) string {
|
||||
return fmt.Sprintf("%s_%d", r.collectionBaseName, dimension)
|
||||
}
|
||||
|
||||
func (r *repository) baseFilter(params types.RetrieveParams) *tcvectordb.Filter {
|
||||
conditions := []string{fmt.Sprintf("%s=1", fieldIsEnabled)}
|
||||
if len(params.KnowledgeBaseIDs) > 0 {
|
||||
conditions = append(conditions, tcvectordb.In(fieldKnowledgeBaseID, params.KnowledgeBaseIDs))
|
||||
}
|
||||
if len(params.KnowledgeIDs) > 0 {
|
||||
conditions = append(conditions, tcvectordb.In(fieldKnowledgeID, params.KnowledgeIDs))
|
||||
}
|
||||
if len(params.TagIDs) > 0 {
|
||||
conditions = append(conditions, tcvectordb.In(fieldTagID, params.TagIDs))
|
||||
}
|
||||
if len(params.ExcludeKnowledgeIDs) > 0 {
|
||||
conditions = append(conditions, tcvectordb.NotIn(fieldKnowledgeID, params.ExcludeKnowledgeIDs))
|
||||
}
|
||||
if len(params.ExcludeChunkIDs) > 0 {
|
||||
conditions = append(conditions, tcvectordb.NotIn(fieldChunkID, params.ExcludeChunkIDs))
|
||||
}
|
||||
return tcvectordb.NewFilter(strings.Join(conditions, " and "))
|
||||
}
|
||||
|
||||
func (r *repository) retrieveResult(results []*types.IndexWithScore, retrieverType types.RetrieverType) []*types.RetrieveResult {
|
||||
return []*types.RetrieveResult{
|
||||
{
|
||||
Results: results,
|
||||
RetrieverEngineType: types.TencentVectorDBRetrieverEngineType,
|
||||
RetrieverType: retrieverType,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func toVectorEmbedding(indexInfo *types.IndexInfo, params map[string]any) *vectorEmbedding {
|
||||
embedding := &vectorEmbedding{
|
||||
ID: indexInfo.ChunkID,
|
||||
Content: cleanInvalidUTF8(indexInfo.Content),
|
||||
SourceID: indexInfo.SourceID,
|
||||
SourceType: int(indexInfo.SourceType),
|
||||
ChunkID: indexInfo.ChunkID,
|
||||
KnowledgeID: indexInfo.KnowledgeID,
|
||||
KnowledgeBaseID: indexInfo.KnowledgeBaseID,
|
||||
TagID: indexInfo.TagID,
|
||||
IsEnabled: indexInfo.IsEnabled,
|
||||
}
|
||||
if embedding.ID == "" {
|
||||
embedding.ID = indexInfo.SourceID
|
||||
}
|
||||
if params != nil && slices.Contains(slices.Collect(maps.Keys(params)), fieldVector) {
|
||||
if embeddingMap, ok := params[fieldVector].(map[string][]float32); ok {
|
||||
embedding.Embedding = lookupEmbedding(embeddingMap, indexInfo)
|
||||
}
|
||||
}
|
||||
if params != nil && slices.Contains(slices.Collect(maps.Keys(params)), "embedding") {
|
||||
if embeddingMap, ok := params["embedding"].(map[string][]float32); ok {
|
||||
embedding.Embedding = lookupEmbedding(embeddingMap, indexInfo)
|
||||
}
|
||||
}
|
||||
return embedding
|
||||
}
|
||||
|
||||
func lookupEmbedding(embeddingMap map[string][]float32, indexInfo *types.IndexInfo) []float32 {
|
||||
if embedding, ok := embeddingMap[indexInfo.SourceID]; ok {
|
||||
return embedding
|
||||
}
|
||||
return embeddingMap[indexInfo.ChunkID]
|
||||
}
|
||||
|
||||
func cleanInvalidUTF8(s string) string {
|
||||
var b strings.Builder
|
||||
b.Grow(len(s))
|
||||
|
||||
for i := 0; i < len(s); {
|
||||
r, size := utf8.DecodeRuneInString(s[i:])
|
||||
if r == utf8.RuneError && size == 1 {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if r == 0 {
|
||||
i += size
|
||||
continue
|
||||
}
|
||||
b.WriteRune(r)
|
||||
i += size
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func toDocument(embedding *vectorEmbedding) tcvectordb.Document {
|
||||
return tcvectordb.Document{
|
||||
Id: embedding.ID,
|
||||
Vector: embedding.Embedding,
|
||||
Fields: map[string]tcvectordb.Field{
|
||||
fieldContent: {Val: embedding.Content},
|
||||
fieldSourceID: {Val: embedding.SourceID},
|
||||
fieldSourceType: {Val: uint64(embedding.SourceType)},
|
||||
fieldChunkID: {Val: embedding.ChunkID},
|
||||
fieldKnowledgeID: {Val: embedding.KnowledgeID},
|
||||
fieldKnowledgeBaseID: {Val: embedding.KnowledgeBaseID},
|
||||
fieldTagID: {Val: embedding.TagID},
|
||||
fieldIsEnabled: {Val: boolToUint64(embedding.IsEnabled)},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func fromDocument(doc tcvectordb.Document) *vectorEmbedding {
|
||||
return &vectorEmbedding{
|
||||
ID: doc.Id,
|
||||
Content: fieldString(doc, fieldContent),
|
||||
SourceID: fieldString(doc, fieldSourceID),
|
||||
SourceType: int(fieldUint64(doc, fieldSourceType)),
|
||||
ChunkID: fieldString(doc, fieldChunkID),
|
||||
KnowledgeID: fieldString(doc, fieldKnowledgeID),
|
||||
KnowledgeBaseID: fieldString(doc, fieldKnowledgeBaseID),
|
||||
TagID: fieldString(doc, fieldTagID),
|
||||
Embedding: doc.Vector,
|
||||
IsEnabled: fieldUint64(doc, fieldIsEnabled) == 1,
|
||||
Score: float64(doc.Score),
|
||||
}
|
||||
}
|
||||
|
||||
func toIndexWithScore(embedding *vectorEmbedding, matchType types.MatchType) *types.IndexWithScore {
|
||||
return &types.IndexWithScore{
|
||||
ID: embedding.ID,
|
||||
Content: embedding.Content,
|
||||
SourceID: embedding.SourceID,
|
||||
SourceType: types.SourceType(embedding.SourceType),
|
||||
ChunkID: embedding.ChunkID,
|
||||
KnowledgeID: embedding.KnowledgeID,
|
||||
KnowledgeBaseID: embedding.KnowledgeBaseID,
|
||||
TagID: embedding.TagID,
|
||||
Score: embedding.Score,
|
||||
MatchType: matchType,
|
||||
IsEnabled: embedding.IsEnabled,
|
||||
}
|
||||
}
|
||||
|
||||
func outputFields() []string {
|
||||
return []string{
|
||||
fieldID,
|
||||
fieldContent,
|
||||
fieldSourceID,
|
||||
fieldSourceType,
|
||||
fieldChunkID,
|
||||
fieldKnowledgeID,
|
||||
fieldKnowledgeBaseID,
|
||||
fieldTagID,
|
||||
fieldIsEnabled,
|
||||
}
|
||||
}
|
||||
|
||||
func fieldString(doc tcvectordb.Document, name string) string {
|
||||
field, ok := doc.Fields[name]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return field.String()
|
||||
}
|
||||
|
||||
func fieldUint64(doc tcvectordb.Document, name string) uint64 {
|
||||
field, ok := doc.Fields[name]
|
||||
if !ok {
|
||||
return 0
|
||||
}
|
||||
return field.Uint64()
|
||||
}
|
||||
|
||||
func boolToUint64(v bool) uint64 {
|
||||
if v {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func defaultIfZero(v, def int) int {
|
||||
if v <= 0 {
|
||||
return def
|
||||
}
|
||||
return v
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package tencentvectordb
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/tencent/vectordatabase-sdk-go/tcvectordb"
|
||||
)
|
||||
|
||||
const (
|
||||
envTencentVectorDBDatabase = "TENCENT_VECTORDB_DATABASE"
|
||||
envTencentVectorDBCollection = "TENCENT_VECTORDB_COLLECTION"
|
||||
defaultDatabaseName = "weknora"
|
||||
defaultCollectionName = "weknora_embeddings"
|
||||
|
||||
fieldID = "id"
|
||||
fieldVector = "vector"
|
||||
fieldContent = "content"
|
||||
fieldSourceID = "source_id"
|
||||
fieldSourceType = "source_type"
|
||||
fieldChunkID = "chunk_id"
|
||||
fieldKnowledgeID = "knowledge_id"
|
||||
fieldKnowledgeBaseID = "knowledge_base_id"
|
||||
fieldTagID = "tag_id"
|
||||
fieldIsEnabled = "is_enabled"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client *tcvectordb.RpcClient
|
||||
databaseName string
|
||||
collectionBaseName string
|
||||
shardsNum int
|
||||
replicasNum int
|
||||
initialized sync.Map
|
||||
}
|
||||
|
||||
type vectorEmbedding struct {
|
||||
ID string
|
||||
Content string
|
||||
SourceID string
|
||||
SourceType int
|
||||
ChunkID string
|
||||
KnowledgeID string
|
||||
KnowledgeBaseID string
|
||||
TagID string
|
||||
Embedding []float32
|
||||
IsEnabled bool
|
||||
Score float64
|
||||
}
|
||||
@@ -16,8 +16,8 @@ import (
|
||||
// vectorStoreService implements interfaces.VectorStoreService
|
||||
type vectorStoreService struct {
|
||||
repo interfaces.VectorStoreRepository
|
||||
storeRegistry interfaces.StoreRegistry // for dynamic registry updates on CRUD
|
||||
factory interfaces.EngineFactory // creates engine services from VectorStore config
|
||||
storeRegistry interfaces.StoreRegistry // for dynamic registry updates on CRUD
|
||||
factory interfaces.EngineFactory // creates engine services from VectorStore config
|
||||
}
|
||||
|
||||
// NewVectorStoreService creates a new vector store service
|
||||
@@ -178,6 +178,16 @@ func validateConnectionConfig(engineType types.RetrieverEngineType, config types
|
||||
if config.Addr == "" {
|
||||
return errors.NewValidationError("addr is required for milvus")
|
||||
}
|
||||
case types.TencentVectorDBRetrieverEngineType:
|
||||
if config.Addr == "" {
|
||||
return errors.NewValidationError("addr is required for tencent_vectordb")
|
||||
}
|
||||
if config.Username == "" {
|
||||
return errors.NewValidationError("username is required for tencent_vectordb")
|
||||
}
|
||||
if config.APIKey == "" {
|
||||
return errors.NewValidationError("api_key is required for tencent_vectordb")
|
||||
}
|
||||
case types.WeaviateRetrieverEngineType:
|
||||
if config.Host == "" {
|
||||
return errors.NewValidationError("host is required for weaviate")
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/go-sql-driver/mysql" // MySQL driver for database/sql, used by Doris connection test
|
||||
_ "github.com/jackc/pgx/v5/stdlib" // pgx driver for database/sql
|
||||
"github.com/qdrant/go-client/qdrant"
|
||||
"github.com/tencent/vectordatabase-sdk-go/tcvectordb"
|
||||
"github.com/weaviate/weaviate-go-client/v5/weaviate"
|
||||
"github.com/weaviate/weaviate-go-client/v5/weaviate/auth"
|
||||
wgrpc "github.com/weaviate/weaviate-go-client/v5/weaviate/grpc"
|
||||
@@ -40,6 +41,8 @@ func (s *vectorStoreService) TestConnection(
|
||||
return testQdrantConnection(ctx, config)
|
||||
case types.MilvusRetrieverEngineType:
|
||||
return testMilvusConnection(ctx, config)
|
||||
case types.TencentVectorDBRetrieverEngineType:
|
||||
return testTencentVectorDBConnection(ctx, config)
|
||||
case types.WeaviateRetrieverEngineType:
|
||||
return testWeaviateConnection(ctx, config)
|
||||
case types.DorisRetrieverEngineType:
|
||||
@@ -180,6 +183,27 @@ func testMilvusConnection(ctx context.Context, config types.ConnectionConfig) (s
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func testTencentVectorDBConnection(ctx context.Context, config types.ConnectionConfig) (string, error) {
|
||||
testCtx, cancel := context.WithTimeout(ctx, connectionTestTimeout)
|
||||
defer cancel()
|
||||
|
||||
client, err := tcvectordb.NewRpcClient(config.Addr, config.Username, config.APIKey, &tcvectordb.ClientOption{
|
||||
ReadConsistency: tcvectordb.EventualConsistency,
|
||||
Timeout: connectionTestTimeout,
|
||||
})
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "Tencent VectorDB connection test failed: %v", err)
|
||||
return "", errors.NewBadRequestError("failed to connect to tencent vectordb: connection refused or authentication failed")
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
if _, err := client.ListDatabase(testCtx); err != nil {
|
||||
logger.Warnf(ctx, "Tencent VectorDB list database failed: %v", err)
|
||||
return "", errors.NewBadRequestError("failed to connect to tencent vectordb: authentication failed or server error")
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func testWeaviateConnection(ctx context.Context, config types.ConnectionConfig) (string, error) {
|
||||
testCtx, cancel := context.WithTimeout(ctx, connectionTestTimeout)
|
||||
defer cancel()
|
||||
|
||||
@@ -42,6 +42,7 @@ import (
|
||||
postgresRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/postgres"
|
||||
qdrantRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/qdrant"
|
||||
sqliteRetrieverRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/sqlite"
|
||||
tencentVectorDBRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/tencentvectordb"
|
||||
weaviateRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/weaviate"
|
||||
"github.com/Tencent/WeKnora/internal/application/service"
|
||||
chatpipeline "github.com/Tencent/WeKnora/internal/application/service/chat_pipeline"
|
||||
@@ -78,6 +79,7 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/tencent/vectordatabase-sdk-go/tcvectordb"
|
||||
"github.com/weaviate/weaviate-go-client/v5/weaviate"
|
||||
"github.com/weaviate/weaviate-go-client/v5/weaviate/auth"
|
||||
wgrpc "github.com/weaviate/weaviate-go-client/v5/weaviate/grpc"
|
||||
@@ -1003,6 +1005,37 @@ func initRetrieveEngineRegistry(db *gorm.DB, cfg *config.Config) (interfaces.Ret
|
||||
}
|
||||
}
|
||||
}
|
||||
if slices.Contains(retrieveDriver, "tencent_vectordb") {
|
||||
addr := os.Getenv("TENCENT_VECTORDB_ADDR")
|
||||
username := os.Getenv("TENCENT_VECTORDB_USERNAME")
|
||||
apiKey := os.Getenv("TENCENT_VECTORDB_API_KEY")
|
||||
if addr == "" || username == "" || apiKey == "" {
|
||||
log.Errorf("Missing Tencent VectorDB configuration")
|
||||
} else {
|
||||
client, err := tcvectordb.NewRpcClient(addr, username, apiKey, &tcvectordb.ClientOption{
|
||||
ReadConsistency: tcvectordb.EventualConsistency,
|
||||
Timeout: 10 * time.Second,
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorf("Create tencent_vectordb client failed: %v", err)
|
||||
} else {
|
||||
tencentRepository := tencentVectorDBRepo.NewTencentVectorDBRetrieveEngineRepository(
|
||||
client,
|
||||
os.Getenv("TENCENT_VECTORDB_DATABASE"),
|
||||
nil,
|
||||
)
|
||||
if err := registry.Register(
|
||||
retriever.NewKVHybridRetrieveEngine(
|
||||
tencentRepository, types.TencentVectorDBRetrieverEngineType,
|
||||
),
|
||||
); err != nil {
|
||||
log.Errorf("Register tencent_vectordb retrieve engine failed: %v", err)
|
||||
} else {
|
||||
log.Infof("Register tencent_vectordb retrieve engine success")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// ─── DB store registration (byStoreID) ───
|
||||
if storeReg, ok := registry.(*retriever.RetrieveEngineRegistry); ok {
|
||||
loadDBStoresIntoRegistry(storeReg, db, cfg)
|
||||
|
||||
@@ -26,11 +26,13 @@ import (
|
||||
postgresRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/postgres"
|
||||
qdrantRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/qdrant"
|
||||
sqliteRetrieverRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/sqlite"
|
||||
tencentVectorDBRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/tencentvectordb"
|
||||
weaviateRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/weaviate"
|
||||
"github.com/Tencent/WeKnora/internal/application/service/retriever"
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/tencent/vectordatabase-sdk-go/tcvectordb"
|
||||
)
|
||||
|
||||
// NewEngineFactory returns an EngineFactory function closed over db and cfg.
|
||||
@@ -64,6 +66,8 @@ func createEngineServiceFromStore(
|
||||
return createDorisEngine(store)
|
||||
case types.SQLiteRetrieverEngineType:
|
||||
return createSQLiteEngine(store, db)
|
||||
case types.TencentVectorDBRetrieverEngineType:
|
||||
return createTencentVectorDBEngine(store)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported engine type: %s", store.EngineType)
|
||||
}
|
||||
@@ -264,3 +268,16 @@ func hostFromAddr(addr string) string {
|
||||
}
|
||||
return addr
|
||||
}
|
||||
|
||||
func createTencentVectorDBEngine(store types.VectorStore) (interfaces.RetrieveEngineService, error) {
|
||||
cc := store.ConnectionConfig
|
||||
client, err := tcvectordb.NewRpcClient(cc.Addr, cc.Username, cc.APIKey, &tcvectordb.ClientOption{
|
||||
ReadConsistency: tcvectordb.EventualConsistency,
|
||||
Timeout: 10 * time.Second,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create tencent vectordb client: %w", err)
|
||||
}
|
||||
repo := tencentVectorDBRepo.NewTencentVectorDBRetrieveEngineRepository(client, cc.Database, &store.IndexConfig)
|
||||
return retriever.NewKVHybridRetrieveEngine(repo, types.TencentVectorDBRetrieverEngineType), nil
|
||||
}
|
||||
|
||||
@@ -5,15 +5,16 @@ type RetrieverEngineType string
|
||||
|
||||
// RetrieverEngineType constants
|
||||
const (
|
||||
PostgresRetrieverEngineType RetrieverEngineType = "postgres"
|
||||
ElasticsearchRetrieverEngineType RetrieverEngineType = "elasticsearch"
|
||||
InfinityRetrieverEngineType RetrieverEngineType = "infinity"
|
||||
ElasticFaissRetrieverEngineType RetrieverEngineType = "elasticfaiss"
|
||||
QdrantRetrieverEngineType RetrieverEngineType = "qdrant"
|
||||
MilvusRetrieverEngineType RetrieverEngineType = "milvus"
|
||||
WeaviateRetrieverEngineType RetrieverEngineType = "weaviate"
|
||||
DorisRetrieverEngineType RetrieverEngineType = "doris"
|
||||
SQLiteRetrieverEngineType RetrieverEngineType = "sqlite"
|
||||
PostgresRetrieverEngineType RetrieverEngineType = "postgres"
|
||||
ElasticsearchRetrieverEngineType RetrieverEngineType = "elasticsearch"
|
||||
InfinityRetrieverEngineType RetrieverEngineType = "infinity"
|
||||
ElasticFaissRetrieverEngineType RetrieverEngineType = "elasticfaiss"
|
||||
QdrantRetrieverEngineType RetrieverEngineType = "qdrant"
|
||||
MilvusRetrieverEngineType RetrieverEngineType = "milvus"
|
||||
WeaviateRetrieverEngineType RetrieverEngineType = "weaviate"
|
||||
DorisRetrieverEngineType RetrieverEngineType = "doris"
|
||||
SQLiteRetrieverEngineType RetrieverEngineType = "sqlite"
|
||||
TencentVectorDBRetrieverEngineType RetrieverEngineType = "tencent_vectordb"
|
||||
)
|
||||
|
||||
// RetrieverType represents the type of retriever
|
||||
|
||||
@@ -68,13 +68,14 @@ func (v *VectorStore) BeforeCreate(tx *gorm.DB) error {
|
||||
// InfinityRetrieverEngineType and ElasticFaissRetrieverEngineType are legacy/experimental
|
||||
// types that do not have standalone deployable instances, so they are excluded.
|
||||
var validEngineTypes = map[RetrieverEngineType]bool{
|
||||
PostgresRetrieverEngineType: true,
|
||||
ElasticsearchRetrieverEngineType: true,
|
||||
QdrantRetrieverEngineType: true,
|
||||
MilvusRetrieverEngineType: true,
|
||||
WeaviateRetrieverEngineType: true,
|
||||
DorisRetrieverEngineType: true,
|
||||
SQLiteRetrieverEngineType: true,
|
||||
PostgresRetrieverEngineType: true,
|
||||
ElasticsearchRetrieverEngineType: true,
|
||||
QdrantRetrieverEngineType: true,
|
||||
MilvusRetrieverEngineType: true,
|
||||
WeaviateRetrieverEngineType: true,
|
||||
DorisRetrieverEngineType: true,
|
||||
SQLiteRetrieverEngineType: true,
|
||||
TencentVectorDBRetrieverEngineType: true,
|
||||
}
|
||||
|
||||
// IsValidEngineType checks whether the given engine type is valid for VectorStore.
|
||||
@@ -115,14 +116,14 @@ type ConnectionConfig struct {
|
||||
// Weaviate
|
||||
GrpcAddress string `yaml:"grpc_address" json:"grpc_address,omitempty"`
|
||||
Scheme string `yaml:"scheme" json:"scheme,omitempty"`
|
||||
// Tencent VectorDB and Doris database name.
|
||||
Database string `yaml:"database" json:"database,omitempty"`
|
||||
// Postgres
|
||||
UseDefaultConnection bool `yaml:"use_default_connection" json:"use_default_connection,omitempty"`
|
||||
// Doris: HTTP port for Stream Load API (FE default 8030).
|
||||
// Addr is reused for the MySQL protocol "host:9030"; HTTPPort + the host of Addr
|
||||
// together form the FE HTTP endpoint used by Stream Load.
|
||||
HTTPPort int `yaml:"http_port" json:"http_port,omitempty"`
|
||||
// Doris: target database name for the Stream Load HTTP path and the MySQL DSN.
|
||||
Database string `yaml:"database" json:"database,omitempty"`
|
||||
// Version is the detected server version (e.g., "7.10.1", "16.2", "1.12.6").
|
||||
// Auto-populated by TestConnection on successful connectivity check.
|
||||
Version string `yaml:"version" json:"version,omitempty"`
|
||||
@@ -175,6 +176,9 @@ func (c *ConnectionConfig) Scan(value interface{}) error {
|
||||
// GetEndpoint returns a normalized endpoint string for duplicate detection.
|
||||
func (c ConnectionConfig) GetEndpoint() string {
|
||||
if c.Addr != "" {
|
||||
if c.Database != "" {
|
||||
return c.Addr + "/" + c.Database
|
||||
}
|
||||
return c.Addr
|
||||
}
|
||||
if c.Host != "" {
|
||||
@@ -218,12 +222,12 @@ type IndexConfig struct {
|
||||
|
||||
// --- 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
|
||||
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
|
||||
BucketsNum int `yaml:"buckets_num" json:"buckets_num,omitempty"` // Doris: number of buckets per table (DISTRIBUTED BY HASH ... BUCKETS N)
|
||||
ReplicationNum int `yaml:"replication_num" json:"replication_num,omitempty"` // Doris: replication_num PROPERTIES
|
||||
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
|
||||
BucketsNum int `yaml:"buckets_num" json:"buckets_num,omitempty"` // Doris: number of buckets per table (DISTRIBUTED BY HASH ... BUCKETS N)
|
||||
ReplicationNum int `yaml:"replication_num" json:"replication_num,omitempty"` // Doris: replication_num PROPERTIES
|
||||
}
|
||||
|
||||
// Value implements the driver.Valuer interface.
|
||||
@@ -262,6 +266,11 @@ func (c IndexConfig) GetIndexNameOrDefault(engineType RetrieverEngineType) strin
|
||||
return c.CollectionName
|
||||
}
|
||||
return "weknora_embeddings"
|
||||
case TencentVectorDBRetrieverEngineType:
|
||||
if c.CollectionName != "" {
|
||||
return c.CollectionName
|
||||
}
|
||||
return "weknora_embeddings"
|
||||
case WeaviateRetrieverEngineType:
|
||||
if c.CollectionPrefix != "" {
|
||||
return c.CollectionPrefix
|
||||
@@ -568,6 +577,21 @@ func GetVectorStoreTypes() []VectorStoreTypeInfo {
|
||||
{Name: "replica_number", Type: "number", Required: false, Description: "In-memory Replicas (read HA)", Default: 1},
|
||||
},
|
||||
},
|
||||
{
|
||||
Type: "tencent_vectordb",
|
||||
DisplayName: "Tencent VectorDB",
|
||||
ConnectionFields: []VectorStoreFieldInfo{
|
||||
{Name: "addr", Type: "string", Required: true, Description: "Address", Default: "http://localhost:8080"},
|
||||
{Name: "username", Type: "string", Required: true, Description: "Username"},
|
||||
{Name: "api_key", Type: "string", Required: true, Sensitive: true, Description: "API Key"},
|
||||
{Name: "database", Type: "string", Required: false, Description: "Database", Default: "weknora"},
|
||||
},
|
||||
IndexFields: []VectorStoreFieldInfo{
|
||||
{Name: "collection_name", Type: "string", Required: false, Description: "Collection Name", Default: "weknora_embeddings"},
|
||||
{Name: "shards_num", Type: "number", Required: false, Description: "Shards", Default: 1},
|
||||
{Name: "replica_number", Type: "number", Required: false, Description: "Replicas", Default: 1},
|
||||
},
|
||||
},
|
||||
{
|
||||
Type: "weaviate",
|
||||
DisplayName: "Weaviate",
|
||||
@@ -714,6 +738,21 @@ func buildEnvStoreForDriver(driver string, envLookup EnvLookupFunc) *VectorStore
|
||||
Password: envLookup("MILVUS_PASSWORD"),
|
||||
},
|
||||
}
|
||||
case "tencent_vectordb":
|
||||
return &VectorStore{
|
||||
ID: "__env_tencent_vectordb__",
|
||||
Name: "Tencent VectorDB",
|
||||
EngineType: TencentVectorDBRetrieverEngineType,
|
||||
ConnectionConfig: ConnectionConfig{
|
||||
Addr: envLookup("TENCENT_VECTORDB_ADDR"),
|
||||
Username: envLookup("TENCENT_VECTORDB_USERNAME"),
|
||||
APIKey: envLookup("TENCENT_VECTORDB_API_KEY"),
|
||||
Database: envLookup("TENCENT_VECTORDB_DATABASE"),
|
||||
},
|
||||
IndexConfig: IndexConfig{
|
||||
CollectionName: envLookup("TENCENT_VECTORDB_COLLECTION"),
|
||||
},
|
||||
}
|
||||
case "weaviate":
|
||||
return &VectorStore{
|
||||
ID: "__env_weaviate__",
|
||||
|
||||
@@ -43,20 +43,25 @@ func TestIsEnvStoreID(t *testing.T) {
|
||||
|
||||
func TestBuildEnvVectorStores(t *testing.T) {
|
||||
envMap := map[string]string{
|
||||
"ELASTICSEARCH_ADDR": "http://es:9200",
|
||||
"ELASTICSEARCH_USERNAME": "elastic",
|
||||
"ELASTICSEARCH_PASSWORD": "secret",
|
||||
"ELASTICSEARCH_INDEX": "my_index",
|
||||
"QDRANT_HOST": "qdrant-host",
|
||||
"QDRANT_API_KEY": "qd-key",
|
||||
"MILVUS_ADDRESS": "milvus:19530",
|
||||
"WEAVIATE_HOST": "weaviate:8080",
|
||||
"DORIS_ADDR": "doris-fe:9030",
|
||||
"DORIS_HTTP_PORT": "8030",
|
||||
"DORIS_DATABASE": "weknora",
|
||||
"DORIS_USERNAME": "root",
|
||||
"DORIS_PASSWORD": "doris-pass",
|
||||
"DORIS_TABLE_PREFIX": "weknora_embeddings",
|
||||
"ELASTICSEARCH_ADDR": "http://es:9200",
|
||||
"ELASTICSEARCH_USERNAME": "elastic",
|
||||
"ELASTICSEARCH_PASSWORD": "secret",
|
||||
"ELASTICSEARCH_INDEX": "my_index",
|
||||
"QDRANT_HOST": "qdrant-host",
|
||||
"QDRANT_API_KEY": "qd-key",
|
||||
"MILVUS_ADDRESS": "milvus:19530",
|
||||
"TENCENT_VECTORDB_ADDR": "http://tencent-vdb",
|
||||
"TENCENT_VECTORDB_USERNAME": "root",
|
||||
"TENCENT_VECTORDB_API_KEY": "vdb-key",
|
||||
"TENCENT_VECTORDB_DATABASE": "weknora",
|
||||
"TENCENT_VECTORDB_COLLECTION": "weknora_embeddings",
|
||||
"WEAVIATE_HOST": "weaviate:8080",
|
||||
"DORIS_ADDR": "doris-fe:9030",
|
||||
"DORIS_HTTP_PORT": "8030",
|
||||
"DORIS_DATABASE": "weknora",
|
||||
"DORIS_USERNAME": "root",
|
||||
"DORIS_PASSWORD": "doris-pass",
|
||||
"DORIS_TABLE_PREFIX": "weknora_embeddings",
|
||||
}
|
||||
lookup := mockEnvLookup(envMap)
|
||||
|
||||
@@ -103,8 +108,8 @@ func TestBuildEnvVectorStores(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("all supported drivers", func(t *testing.T) {
|
||||
stores := BuildEnvVectorStores("postgres,sqlite,elasticsearch_v8,elasticsearch_v7,qdrant,milvus,weaviate,doris", lookup)
|
||||
require.Len(t, stores, 8)
|
||||
stores := BuildEnvVectorStores("postgres,sqlite,elasticsearch_v8,elasticsearch_v7,qdrant,milvus,weaviate,doris,tencent_vectordb", lookup)
|
||||
require.Len(t, stores, 9)
|
||||
|
||||
ids := make([]string, len(stores))
|
||||
for i, s := range stores {
|
||||
@@ -118,6 +123,7 @@ func TestBuildEnvVectorStores(t *testing.T) {
|
||||
assert.Contains(t, ids, "__env_milvus__")
|
||||
assert.Contains(t, ids, "__env_weaviate__")
|
||||
assert.Contains(t, ids, "__env_doris__")
|
||||
assert.Contains(t, ids, "__env_tencent_vectordb__")
|
||||
})
|
||||
|
||||
t.Run("qdrant env store", func(t *testing.T) {
|
||||
@@ -133,6 +139,16 @@ func TestBuildEnvVectorStores(t *testing.T) {
|
||||
assert.Equal(t, "milvus:19530", stores[0].ConnectionConfig.Addr)
|
||||
})
|
||||
|
||||
t.Run("tencent vectordb env store", func(t *testing.T) {
|
||||
stores := BuildEnvVectorStores("tencent_vectordb", lookup)
|
||||
require.Len(t, stores, 1)
|
||||
assert.Equal(t, "http://tencent-vdb", stores[0].ConnectionConfig.Addr)
|
||||
assert.Equal(t, "root", stores[0].ConnectionConfig.Username)
|
||||
assert.Equal(t, "vdb-key", stores[0].ConnectionConfig.APIKey)
|
||||
assert.Equal(t, "weknora", stores[0].ConnectionConfig.Database)
|
||||
assert.Equal(t, "weknora_embeddings", stores[0].IndexConfig.CollectionName)
|
||||
})
|
||||
|
||||
t.Run("weaviate env store", func(t *testing.T) {
|
||||
stores := BuildEnvVectorStores("weaviate", lookup)
|
||||
require.Len(t, stores, 1)
|
||||
@@ -229,8 +245,8 @@ func TestNewVectorStoreResponse(t *testing.T) {
|
||||
func TestGetVectorStoreTypes(t *testing.T) {
|
||||
types := GetVectorStoreTypes()
|
||||
|
||||
t.Run("returns 5 engine types (excludes postgres and sqlite)", func(t *testing.T) {
|
||||
assert.Len(t, types, 5)
|
||||
t.Run("returns supported external engine types (excludes postgres and sqlite)", func(t *testing.T) {
|
||||
assert.Len(t, types, 6)
|
||||
})
|
||||
|
||||
t.Run("type names match engine constants", func(t *testing.T) {
|
||||
@@ -241,6 +257,7 @@ func TestGetVectorStoreTypes(t *testing.T) {
|
||||
assert.Contains(t, typeNames, "elasticsearch")
|
||||
assert.Contains(t, typeNames, "qdrant")
|
||||
assert.Contains(t, typeNames, "milvus")
|
||||
assert.Contains(t, typeNames, "tencent_vectordb")
|
||||
assert.Contains(t, typeNames, "weaviate")
|
||||
assert.Contains(t, typeNames, "doris")
|
||||
assert.NotContains(t, typeNames, "postgres")
|
||||
@@ -369,6 +386,7 @@ func TestIsValidEngineType(t *testing.T) {
|
||||
MilvusRetrieverEngineType,
|
||||
WeaviateRetrieverEngineType,
|
||||
SQLiteRetrieverEngineType,
|
||||
TencentVectorDBRetrieverEngineType,
|
||||
}
|
||||
for _, et := range validTypes {
|
||||
t.Run("valid: "+string(et), func(t *testing.T) {
|
||||
@@ -659,6 +677,19 @@ func TestIndexConfig_GetIndexNameOrDefault(t *testing.T) {
|
||||
engineType: MilvusRetrieverEngineType,
|
||||
expected: "weknora_embeddings",
|
||||
},
|
||||
// Tencent VectorDB
|
||||
{
|
||||
name: "tencent vectordb with custom collection name",
|
||||
config: IndexConfig{CollectionName: "custom_collection"},
|
||||
engineType: TencentVectorDBRetrieverEngineType,
|
||||
expected: "custom_collection",
|
||||
},
|
||||
{
|
||||
name: "tencent vectordb default",
|
||||
config: IndexConfig{},
|
||||
engineType: TencentVectorDBRetrieverEngineType,
|
||||
expected: "weknora_embeddings",
|
||||
},
|
||||
// Weaviate
|
||||
{
|
||||
name: "weaviate with custom prefix",
|
||||
|
||||
Reference in New Issue
Block a user