feat: add Tencent VectorDB retriever backend
This commit is contained in:
+17
-1
@@ -120,7 +120,7 @@ OLLAMA_BASE_URL=http://host.docker.internal:11434
|
||||
# 主数据库类型(postgres/mysql)
|
||||
DB_DRIVER=postgres
|
||||
|
||||
# 向量存储类型(postgres/elasticsearch_v7/elasticsearch_v8/qdrant/milvus/weaviate/doris)
|
||||
# 向量存储类型(postgres/elasticsearch_v7/elasticsearch_v8/qdrant/milvus/weaviate/doris/tencent_vectordb)
|
||||
RETRIEVE_DRIVER=postgres
|
||||
|
||||
# 允许用户使用哪些文件存储类型,使用逗号分隔,留空则允许所有类型的存储
|
||||
@@ -250,6 +250,22 @@ CONCURRENCY_POOL_SIZE=5
|
||||
# 是否启用TLS加密连接(可选,默认为false)
|
||||
# QDRANT_USE_TLS=false
|
||||
|
||||
# 如果使用腾讯云 Tencent VectorDB 作为向量存储,需要配置以下参数
|
||||
# Tencent VectorDB 访问地址
|
||||
# TENCENT_VECTORDB_ADDR=http://your-instance.tencentvectordb.com
|
||||
|
||||
# Tencent VectorDB 用户名
|
||||
# TENCENT_VECTORDB_USERNAME=root
|
||||
|
||||
# Tencent VectorDB API Key
|
||||
# TENCENT_VECTORDB_API_KEY=your_tencent_vectordb_api_key
|
||||
|
||||
# Tencent VectorDB 数据库名称(可选,默认 weknora)
|
||||
# TENCENT_VECTORDB_DATABASE=weknora
|
||||
|
||||
# Tencent VectorDB 集合名前缀(可选,默认 weknora_embeddings;实际集合会按向量维度追加后缀)
|
||||
# TENCENT_VECTORDB_COLLECTION=weknora_embeddings
|
||||
|
||||
# 如果使用MinIO作为文件存储,需要配置以下参数
|
||||
# MinIO访问端点(host:port),连接外部MinIO时需修改
|
||||
# MINIO_ENDPOINT=minio:9000
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
[返回目录](./README.md)
|
||||
|
||||
向量存储(VectorStore)API 用于管理向量数据库连接配置。支持 Elasticsearch、PostgreSQL、Qdrant、Milvus、Weaviate、SQLite 六种引擎类型。
|
||||
向量存储(VectorStore)API 用于管理向量数据库连接配置。支持 Elasticsearch、PostgreSQL、Qdrant、Milvus、Weaviate、Tencent VectorDB、SQLite 七种引擎类型。
|
||||
|
||||
| 方法 | 路径 | 描述 |
|
||||
| ------ | ---------------------------- | ------------------------------ |
|
||||
@@ -110,6 +110,8 @@ curl --location 'http://localhost:8080/api/v1/vector-stores/test' \
|
||||
|
||||
创建一个新的向量存储配置。同一 endpoint + index 组合不允许重复注册(包括环境变量配置的存储)。
|
||||
|
||||
Tencent VectorDB 使用 `engine_type: "tencent_vectordb"`。`connection_config` 中 `addr`、`username`、`api_key` 为必填,`database` 可选;`index_config.collection_name` 表示集合名前缀,实际集合会按向量维度追加后缀,例如 `weknora_embeddings_768`。
|
||||
|
||||
**请求**:
|
||||
|
||||
```curl
|
||||
@@ -130,6 +132,27 @@ curl --location 'http://localhost:8080/api/v1/vector-stores' \
|
||||
}'
|
||||
```
|
||||
|
||||
**Tencent VectorDB 请求示例**:
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/vector-stores' \
|
||||
--header 'X-API-Key: sk-xxxxx' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{
|
||||
"name": "tencent-vectordb",
|
||||
"engine_type": "tencent_vectordb",
|
||||
"connection_config": {
|
||||
"addr": "http://your-instance.tencentvectordb.com",
|
||||
"username": "root",
|
||||
"api_key": "your_api_key",
|
||||
"database": "weknora"
|
||||
},
|
||||
"index_config": {
|
||||
"collection_name": "weknora_embeddings"
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
**响应** (201):
|
||||
|
||||
```json
|
||||
|
||||
@@ -61,6 +61,7 @@ YOUR_DATABASE_PASSWORD=password
|
||||
- ElasticsearchV7: `internal/application/repository/retriever/elasticsearch/v7/`
|
||||
- ElasticsearchV8: `internal/application/repository/retriever/elasticsearch/v8/`
|
||||
- Apache Doris 4.1: `internal/application/repository/retriever/doris/`
|
||||
- Tencent VectorDB: `internal/application/repository/retriever/tencentvectordb/`
|
||||
|
||||
## Apache Doris 4.1 集成要点
|
||||
|
||||
@@ -87,6 +88,21 @@ DORIS_TABLE_PREFIX=weknora_embeddings
|
||||
|
||||
启动方式:`docker compose --profile doris up -d`,然后在 FE 上 `CREATE DATABASE weknora;`。
|
||||
|
||||
## Tencent VectorDB
|
||||
|
||||
WeKnora 内置 Tencent VectorDB 适配器,驱动名为 `tencent_vectordb`。该适配器支持向量检索和索引管理,关键词检索不在当前适配器范围内。
|
||||
|
||||
```env
|
||||
RETRIEVE_DRIVER=tencent_vectordb
|
||||
TENCENT_VECTORDB_ADDR=http://your-instance.tencentvectordb.com
|
||||
TENCENT_VECTORDB_USERNAME=root
|
||||
TENCENT_VECTORDB_API_KEY=your_tencent_vectordb_api_key
|
||||
TENCENT_VECTORDB_DATABASE=weknora
|
||||
TENCENT_VECTORDB_COLLECTION=weknora_embeddings
|
||||
```
|
||||
|
||||
`TENCENT_VECTORDB_COLLECTION` 是集合名前缀。WeKnora 会按向量维度创建实际集合,例如 `weknora_embeddings_768`。
|
||||
|
||||
## 相关主题
|
||||
|
||||
- [添加网络搜索引擎](../集成扩展/添加网络搜索引擎.md) — 同类扩展开发模式(接口实现 + 注册 + DI)
|
||||
|
||||
@@ -184,6 +184,7 @@ const (
|
||||
- ElasticsearchV7: `internal/application/repository/retriever/elasticsearch/v7/`
|
||||
- ElasticsearchV8: `internal/application/repository/retriever/elasticsearch/v8/`
|
||||
- Apache Doris 4.1: `internal/application/repository/retriever/doris/`
|
||||
- Tencent VectorDB: `internal/application/repository/retriever/tencentvectordb/`
|
||||
|
||||
通过遵循以上步骤和参考现有实现,你可以成功集成新的向量数据库到 WeKnora 系统中,扩展其向量检索能力。
|
||||
|
||||
@@ -275,5 +276,20 @@ docker exec -it WeKnora-doris-fe mysql -h 127.0.0.1 -P 9030 -uroot \
|
||||
|
||||
随后启动 WeKnora 后端,知识库写入即会按维度自动建表。
|
||||
|
||||
## Tencent VectorDB
|
||||
|
||||
WeKnora 内置 Tencent VectorDB 适配器,驱动名为 `tencent_vectordb`。该适配器支持向量检索和索引管理,关键词检索不在当前适配器范围内。
|
||||
|
||||
### 环境变量示例
|
||||
|
||||
```env
|
||||
RETRIEVE_DRIVER=tencent_vectordb
|
||||
TENCENT_VECTORDB_ADDR=http://your-instance.tencentvectordb.com
|
||||
TENCENT_VECTORDB_USERNAME=root
|
||||
TENCENT_VECTORDB_API_KEY=your_tencent_vectordb_api_key
|
||||
TENCENT_VECTORDB_DATABASE=weknora
|
||||
TENCENT_VECTORDB_COLLECTION=weknora_embeddings
|
||||
```
|
||||
|
||||
`TENCENT_VECTORDB_COLLECTION` 是集合名前缀。WeKnora 会按向量维度创建实际集合,例如 `weknora_embeddings_768`,用于隔离不同 embedding 模型维度的数据。
|
||||
|
||||
|
||||
@@ -53,6 +53,7 @@ require (
|
||||
github.com/swaggo/files v1.0.1
|
||||
github.com/swaggo/gin-swagger v1.6.1
|
||||
github.com/swaggo/swag v1.16.6
|
||||
github.com/tencent/vectordatabase-sdk-go v1.8.4
|
||||
github.com/tencentyun/cos-go-sdk-v5 v0.7.65
|
||||
github.com/tiktoken-go/tokenizer v0.7.0
|
||||
github.com/volcengine/ve-tos-golang-sdk/v2 v2.9.4
|
||||
@@ -148,6 +149,7 @@ require (
|
||||
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
|
||||
github.com/getsentry/sentry-go v0.30.0 // indirect
|
||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||
github.com/go-ego/gse v0.80.3 // indirect
|
||||
github.com/go-ini/ini v1.67.0 // indirect
|
||||
github.com/go-json-experiment/json v0.0.0-20260214004413-d219187c3433 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
@@ -280,6 +282,7 @@ require (
|
||||
github.com/ugorji/go/codec v1.3.0 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasttemplate v1.2.2 // indirect
|
||||
github.com/vcaesar/cedar v0.20.2 // indirect
|
||||
github.com/wailsapp/go-webview2 v1.0.22 // indirect
|
||||
github.com/wailsapp/mimetype v1.4.1 // indirect
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
|
||||
|
||||
@@ -1668,6 +1668,8 @@ github.com/gin-gonic/gin v1.4.0/go.mod h1:OW2EZn3DO8Ln9oIKOvM++LBO+5UPHJJDH72/q/
|
||||
github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=
|
||||
github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=
|
||||
github.com/go-check/check v0.0.0-20180628173108-788fd7840127/go.mod h1:9ES+weclKsC9YodN5RgxqK/VD9HM9JsCSh7rNhMZE98=
|
||||
github.com/go-ego/gse v0.80.3 h1:YNFkjMhlhQnUeuoFcUEd1ivh6SOB764rT8GDsEbDiEg=
|
||||
github.com/go-ego/gse v0.80.3/go.mod h1:Gt3A9Ry1Eso2Kza4MRaiZ7f2DTAvActmETY46Lxg0gU=
|
||||
github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q=
|
||||
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
|
||||
github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
|
||||
@@ -2467,6 +2469,8 @@ github.com/swaggo/gin-swagger v1.6.1 h1:Ri06G4gc9N4t4k8hekMigJ9zKTFSlqj/9paAQCQs
|
||||
github.com/swaggo/gin-swagger v1.6.1/go.mod h1:LQ+hJStHakCWRiK/YNYtJOu4mR2FP+pxLnILT/qNiTw=
|
||||
github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI=
|
||||
github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg=
|
||||
github.com/tencent/vectordatabase-sdk-go v1.8.4 h1:jVATTavFzDypX/TOx+eNrOJk7DcOA0U8REH5NEIC2bs=
|
||||
github.com/tencent/vectordatabase-sdk-go v1.8.4/go.mod h1:cb53Vbd9Lnh3mA1CwqV9Jy8MrNsxpIUlrhzBiBE7A2M=
|
||||
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.563/go.mod h1:7sCQWVkxcsR38nffDW057DRGk8mUjK1Ing/EFOK8s8Y=
|
||||
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/kms v1.0.563/go.mod h1:uom4Nvi9W+Qkom0exYiJ9VWJjXwyxtPYTkKkaLMlfE0=
|
||||
github.com/tencentyun/cos-go-sdk-v5 v0.7.65 h1:+WBbfwThfZSbxpf1Dw6fyMwyzVtWBBExqfDJ5giiR2s=
|
||||
@@ -2523,6 +2527,8 @@ github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+
|
||||
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
|
||||
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
|
||||
github.com/valyala/tcplisten v0.0.0-20161114210144-ceec8f93295a/go.mod h1:v3UYOV9WzVtRmSR+PDvWpU/qWl4Wa5LApYYX4ZtKbio=
|
||||
github.com/vcaesar/cedar v0.20.2 h1:TDx7AdZhilKcfE1WvdToTJf5VrC/FXcUOW+KY1upLZ4=
|
||||
github.com/vcaesar/cedar v0.20.2/go.mod h1:lyuGvALuZZDPNXwpzv/9LyxW+8Y6faN7zauFezNsnik=
|
||||
github.com/vmihailenco/bufpool v0.1.11 h1:gOq2WmBrq0i2yW5QJ16ykccQ4wH9UyEsgLm6czKAd94=
|
||||
github.com/vmihailenco/bufpool v0.1.11/go.mod h1:AFf/MOy3l2CFTKbxwt0mp2MwnqjNEs5H/UxrkA5jxTQ=
|
||||
github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8=
|
||||
|
||||
@@ -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