Documentation
¶
Index ¶
- Constants
- Variables
- func ExtensionAs[T Extension](rctx *RecommendContext, name string) (T, bool)
- func GetExtraAs[T any](p *UserProfile, key string) (T, bool)
- func IsDomainError(err error) bool
- func IsNotFound(err error) bool
- func IsNotSupported(err error) bool
- func IsStoreNotFound(err error) bool
- func IsStoreNotSupported(err error) bool
- func IsUnavailable(err error) bool
- func ValidateVectorMetric(metric string) bool
- type ABDecision
- type ABRuntime
- type CFConfig
- type DefaultRecallConfig
- type DomainError
- type Extension
- type FeatureService
- type FeatureUserItemPair
- type Item
- type KeyValueStore
- type MLPredictRequest
- type MLPredictResponse
- type MLService
- type MetricType
- type RecallConfig
- type RecallDataStore
- type RecommendContext
- type ScoredMember
- type SortedSetRangeStore
- type Store
- type UserProfile
- func (p *UserProfile) AddRecentClick(itemID string, maxSize int)
- func (p *UserProfile) AddRecentImpress(itemID string, maxSize int)
- func (p *UserProfile) GetBucket(key string) string
- func (p *UserProfile) GetExtra(key string) (any, bool)
- func (p *UserProfile) GetExtraFloat64(key string) (float64, bool)
- func (p *UserProfile) GetExtraInt(key string) (int, bool)
- func (p *UserProfile) GetExtraString(key string) (string, bool)
- func (p *UserProfile) GetInterestWeight(category string) float64
- func (p *UserProfile) HasInterest(category string, threshold float64) bool
- func (p *UserProfile) SetBucket(key, value string)
- func (p *UserProfile) SetExtra(key string, value any)
- func (p *UserProfile) UpdateInterest(category string, weight float64)
- type VectorCreateCollectionRequest
- type VectorDatabaseService
- type VectorDeleteRequest
- type VectorInsertRequest
- type VectorSearchItem
- type VectorSearchRequest
- type VectorSearchResult
- type VectorService
- type VectorUpdateRequest
Constants ¶
const ( // 通用错误代码 ErrorCodeNotFound = "NOT_FOUND" // 资源不存在 ErrorCodeNotSupported = "NOT_SUPPORTED" // 操作不支持 ErrorCodeInvalidInput = "INVALID_INPUT" // 输入无效 ErrorCodeInternalError = "INTERNAL_ERROR" // 内部错误 )
错误代码常量
const ( ModuleStore = "store" // 存储模块 ModuleFeature = "feature" // 特征模块 ModuleVector = "vector" // 向量模块 ModuleService = "service" // 服务模块 )
模块名称常量
Variables ¶
var ( // ErrStoreNotFound 表示 key 不存在 ErrStoreNotFound = NewDomainError(ModuleStore, ErrorCodeNotFound, "store: key not found") // ErrStoreNotSupported 表示操作不支持 ErrStoreNotSupported = NewDomainError(ModuleStore, ErrorCodeNotSupported, "store: operation not supported") )
Store 错误定义(使用统一的 DomainError)
Functions ¶
func ExtensionAs ¶
func ExtensionAs[T Extension](rctx *RecommendContext, name string) (T, bool)
ExtensionAs 从 RecommendContext 中获取指定名称的 Extension,并做类型断言。 返回目标类型值和是否成功;未注册或类型不匹配均返回 zero value + false。
func GetExtraAs ¶
func GetExtraAs[T any](p *UserProfile, key string) (T, bool)
GetExtraAs 按类型 T 获取扩展属性。若 key 不存在或类型不匹配则返回 (zero, false)。 精确类型匹配使用类型断言;需数值转换时请用 GetExtraFloat64 / GetExtraInt。
func IsStoreNotFound ¶
IsStoreNotFound 检查错误是否为 key 不存在(使用统一的错误检查)
func IsStoreNotSupported ¶
IsStoreNotSupported 检查错误是否为操作不支持(使用统一的错误检查)
Types ¶
type ABDecision ¶
ABDecision 是通用 AB 决策结果结构。 具体平台(GrowthBook/自研)可映射到该结构后在链路中透传。
func GetABDecision ¶
func GetABDecision( ctx context.Context, rctx *RecommendContext, extensionName string, featureKey string, ) (ABDecision, error)
GetABDecision 是 AB 决策快捷函数。 未注入运行时时返回零值决策且不报错,便于链路降级。
type ABRuntime ¶
type ABRuntime interface {
Extension
Decide(ctx context.Context, featureKey string) (ABDecision, error)
}
ABRuntime 是 AB 运行时扩展接口模板。 建议由业务侧实现并通过 RecommendContext.SetExtension 注入。
func ABRuntimeFromContext ¶
func ABRuntimeFromContext(rctx *RecommendContext, extensionName string) (ABRuntime, bool)
ABRuntimeFromContext 从 RecommendContext 提取 ABRuntime。
type CFConfig ¶
type CFConfig interface {
RecallConfig
DefaultTopKSimilarUsers() int
DefaultMinCommonItems() int
DefaultMinCommonUsers() int
}
CFConfig 是协同过滤专用配置接口,继承 RecallConfig 并追加 CF 特有的参数。 仅 UserBasedCF / ItemBasedCF 使用。
type DefaultRecallConfig ¶
type DefaultRecallConfig struct{}
DefaultRecallConfig 同时实现 RecallConfig 和 CFConfig,提供合理默认值。
func (*DefaultRecallConfig) DefaultMinCommonItems ¶
func (c *DefaultRecallConfig) DefaultMinCommonItems() int
func (*DefaultRecallConfig) DefaultMinCommonUsers ¶
func (c *DefaultRecallConfig) DefaultMinCommonUsers() int
func (*DefaultRecallConfig) DefaultTimeout ¶
func (c *DefaultRecallConfig) DefaultTimeout() time.Duration
func (*DefaultRecallConfig) DefaultTopKItems ¶
func (c *DefaultRecallConfig) DefaultTopKItems() int
func (*DefaultRecallConfig) DefaultTopKSimilarUsers ¶
func (c *DefaultRecallConfig) DefaultTopKSimilarUsers() int
type DomainError ¶
type DomainError struct {
Code string // 错误代码(如 "NOT_FOUND", "NOT_SUPPORTED")
Message string // 错误消息
Module string // 模块名称(如 "store", "feature", "vector")
Cause error // 底层原因(可选)
}
DomainError 是领域层的统一错误类型。
设计原则:
- 所有领域层错误都使用此类型
- 提供错误代码(Code)和消息(Message)
- 支持错误检查函数(IsXXX)
使用场景:
- Store 错误:NOT_FOUND, NOT_SUPPORTED
- Feature 错误:FEATURE_NOT_FOUND, SERVICE_UNAVAILABLE
- Vector 错误:NOT_SUPPORTED
- 其他领域错误
func GetDomainError ¶
func GetDomainError(err error) *DomainError
GetDomainError 从错误链中获取 DomainError,如果不存在则返回 nil
func NewDomainError ¶
func NewDomainError(module, code, message string) *DomainError
NewDomainError 创建新的领域错误
func (*DomainError) Error ¶
func (e *DomainError) Error() string
func (*DomainError) Unwrap ¶
func (e *DomainError) Unwrap() error
type Extension ¶
type Extension interface {
ExtensionName() string // 全局唯一标识,如 "aippy.abtest"
}
Extension 是 RecommendContext 的可插拔扩展接口。 业务方可实现此接口,将 AB 实验、用户画像、限流状态等附加到 Context 上, 在 Pipeline 各 Node 中通过 ExtensionAs 类型安全地读取。
type FeatureService ¶
type FeatureService interface {
// Name 返回特征服务名称(用于日志/监控)
Name() string
// GetUserFeatures 获取用户特征(单个用户)
GetUserFeatures(ctx context.Context, userID string) (map[string]float64, error)
// BatchGetUserFeatures 批量获取用户特征(推荐使用,减少网络往返)
BatchGetUserFeatures(ctx context.Context, userIDs []string) (map[string]map[string]float64, error)
// GetItemFeatures 获取物品特征(单个物品)
GetItemFeatures(ctx context.Context, itemID string) (map[string]float64, error)
// BatchGetItemFeatures 批量获取物品特征(推荐使用,减少网络往返)
BatchGetItemFeatures(ctx context.Context, itemIDs []string) (map[string]map[string]float64, error)
// GetRealtimeFeatures 获取用户-物品实时交叉特征
GetRealtimeFeatures(ctx context.Context, userID, itemID string) (map[string]float64, error)
// BatchGetRealtimeFeatures 批量获取用户-物品实时交叉特征(推荐使用,减少网络往返)
BatchGetRealtimeFeatures(ctx context.Context, pairs []FeatureUserItemPair) (map[FeatureUserItemPair]map[string]float64, error)
// Close 关闭特征服务,释放资源
Close(ctx context.Context) error
}
FeatureService 是特征服务的领域接口。
设计原则:
- 定义在领域层(core),由基础设施层(feature)实现
- 遵循依赖倒置原则:领域层定义接口,基础设施层实现接口
- 避免循环依赖:领域层不依赖基础设施层
使用场景:
- 获取用户特征:用户画像、历史行为等
- 获取物品特征:物品属性、统计特征等
- 获取实时特征:用户-物品交叉实时特征(如实时 CTR、实时交互等)
注意:请求级上下文特征(如 latitude、time_of_day 等)应通过 RecommendContext.Params 传递, 而不是通过 FeatureService 获取。
实现:
- feature.BaseFeatureService 实现此接口
- 其他特征服务(Feast、Redis、HTTP 等)也可以实现此接口
type FeatureUserItemPair ¶
FeatureUserItemPair 用户-物品对,用于批量获取实时特征。
type Item ¶
type Item struct {
ID string // 使用 string 类型(通用,支持所有 ID 格式)
Score float64
Features map[string]float64
Meta map[string]any
Labels map[string]utils.Label
// LabelMergeStrategy 自定义 Label 合并策略(可选)
// 如果为 nil,则使用默认策略
LabelMergeStrategy utils.LabelMergeStrategy
}
Item 是推荐链路中的统一承载结构:特征、分数、元信息、标签。 Labels 用于解释与策略驱动;Score 用于排序决策。
ID 类型设计:
- 使用 string 类型(通用,支持所有 ID 格式)
func (*Item) GetValue ¶
GetValue 从 Item 中按优先级查找 key 对应的字符串值。 查找顺序:Labels > Meta > Features。 用于 Diversity、Filter 等需要统一读取字段的场景, 避免各模块重复实现多字段查找逻辑。
func (*Item) GetValueString ¶
type KeyValueStore ¶
type KeyValueStore interface {
Store
// ZAdd 向有序集合添加成员(用于热门排序、时间线等)
ZAdd(ctx context.Context, key string, score float64, member string) error
// ZRange 按分数降序获取有序集合成员(用于 TopN 召回)。
// 注意:本接口约定为降序(高分在前),与 Redis 原生 ZRANGE(升序)不同。
// 实现 Redis 适配器时应在内部调用 ZREVRANGE 以满足此约定。
ZRange(ctx context.Context, key string, start, stop int64) ([]string, error)
// ZScore 获取成员的分数
ZScore(ctx context.Context, key string, member string) (float64, error)
// HGet 读取 Hash 字段(用于物品元数据、特征)
HGet(ctx context.Context, key, field string) ([]byte, error)
// HSet 写入 Hash 字段
HSet(ctx context.Context, key, field string, value []byte) error
// HGetAll 读取整个 Hash(用于批量特征)
HGetAll(ctx context.Context, key string) (map[string][]byte, error)
}
KeyValueStore 是 Store 的扩展接口,支持更丰富的 KV 操作。
扩展功能:
- 有序集合(SortedSet):用于热门排序、时间线等
- 哈希表(Hash):用于物品元数据、特征等
如果后端不支持某些操作,可返回 ErrStoreNotSupported。
type MLPredictRequest ¶
type MLPredictRequest struct {
// Instances 特征实例列表(每个实例是一个特征向量)
// 格式:[[f1, f2, f3, ...], [f1, f2, f3, ...], ...]
Instances [][]float64
// Features 特征字典列表(可选,与 Instances 二选一)
// 格式:[{"feature1": 0.1, "feature2": 0.2}, ...]
Features []map[string]float64
// ModelName 模型名称(可选,如果服务支持多模型)
ModelName string
// ModelVersion 模型版本(可选)
ModelVersion string
// SignatureName 签名名称(可选,TF Serving 使用)
SignatureName string
// Params 额外参数(可选)
Params map[string]interface{}
}
MLPredictRequest 预测请求
type MLPredictResponse ¶
type MLPredictResponse struct {
// Predictions 预测结果列表(与请求实例一一对应)
Predictions []float64
// Outputs 原始输出(可选,用于调试)
Outputs interface{}
// ModelVersion 模型版本(如果服务返回)
ModelVersion string
}
MLPredictResponse 预测响应
type MLService ¶
type MLService interface {
// Predict 批量预测
Predict(ctx context.Context, req *MLPredictRequest) (*MLPredictResponse, error)
// Health 健康检查
Health(ctx context.Context) error
// Close 关闭连接
Close(ctx context.Context) error
}
MLService 是机器学习服务的领域接口。
设计原则:
- 定义在领域层(core),由基础设施层(service)实现
- 遵循依赖倒置原则:领域层定义接口,基础设施层实现接口
- 避免循环依赖:领域层不依赖基础设施层
使用场景:
- 双塔模型召回:用户塔推理
- 排序模型:LR、DNN、DIN、Wide&Deep 等
- 外部模型服务:TensorFlow Serving、TorchServe、ONNX Runtime 等
实现:
- service.KServeClient 实现此接口(推荐,KServe V2 / Open Inference Protocol 行业标准)
- service.TFServingClient 实现此接口
- service.TorchServeClient 实现此接口(兼容旧 TorchServe 部署)
- 其他模型服务也可以实现此接口
type MetricType ¶
type MetricType string
MetricType 距离度量类型(用于类型安全) 注意:验证函数统一使用 core.ValidateVectorMetric
const ( MetricCosine MetricType = "cosine" MetricEuclidean MetricType = "euclidean" MetricInnerProduct MetricType = "inner_product" )
type RecallConfig ¶
RecallConfig 是通用召回配置接口(所有召回算法均可使用)。
type RecallDataStore ¶
type RecallDataStore interface {
// Name 返回存储后端名称(用于日志/监控)
Name() string
// GetUserItems 获取用户交互过的物品及其评分/权重
// 返回 map[itemID]score,score 可以是评分、点击次数、时长等
GetUserItems(ctx context.Context, userID string) (map[string]float64, error)
// GetItemUsers 获取与物品交互过的用户及其评分/权重
// 返回 map[userID]score
GetItemUsers(ctx context.Context, itemID string) (map[string]float64, error)
// GetItemFeatures 获取物品的内容特征(类别、标签、关键词等)
GetItemFeatures(ctx context.Context, itemID string) (map[string]float64, error)
// GetUserPreferences 获取用户的偏好特征(喜欢的类别、标签等)
GetUserPreferences(ctx context.Context, userID string) (map[string]float64, error)
// GetSimilarItems 根据物品特征获取相似物品(可选,用于优化)
GetSimilarItems(ctx context.Context, itemFeatures map[string]float64, topK int) ([]string, error)
// GetUserVector 获取用户的隐向量
GetUserVector(ctx context.Context, userID string) ([]float64, error)
// GetItemVector 获取物品的隐向量
GetItemVector(ctx context.Context, itemID string) ([]float64, error)
// GetAllItemVectors 获取所有物品的隐向量(用于在线召回)
GetAllItemVectors(ctx context.Context) (map[string][]float64, error)
// GetAllUsers 获取所有用户 ID 列表
GetAllUsers(ctx context.Context) ([]string, error)
// GetAllItems 获取所有物品 ID 列表
GetAllItems(ctx context.Context) ([]string, error)
}
RecallDataStore 是召回数据存储的领域接口。
设计原则:
- 定义在领域层(core),由基础设施层(recall)实现
- 遵循依赖倒置原则:领域层定义接口,基础设施层实现接口
- 统一召回算法的数据访问接口,避免接口爆炸
使用场景:
- 协同过滤:用户-物品交互数据
- 内容推荐:物品特征、用户偏好
- 矩阵分解:用户隐向量、物品隐向量
- 其他召回算法:统一的数据访问接口
实现:
- recall.StoreCFAdapter 实现此接口(基于 core.Store)
- recall.StoreContentAdapter 实现此接口(基于 core.Store)
- recall.StoreMFAdapter 实现此接口(基于 core.Store)
- 其他存储后端也可以实现此接口
type RecommendContext ¶
type RecommendContext struct {
UserID string // 使用 string 类型(通用,支持所有 ID 格式)
DeviceID string
Scene string
// User 是调用方透传的用户对象(any 类型)。
// 框架内置 Node 不会直接读取此字段,仅供自定义 Node 做 type assert。
// 框架读取用户数据的标准通道是 Attributes。
User any
// Attributes 是用户级属性 map,框架读取用户数据的标准通道。
// 包括用户特征(age、gender 等)、向量(user_embedding)、行为序列(recent_clicks)等。
Attributes map[string]any
// Labels 是用户级标签,可驱动整个 Pipeline 行为
// 例如:新用户、重度用户、价格敏感等
Labels map[string]utils.Label
// Params 请求级上下文参数,包含:
// - 请求参数:latitude, longitude, time_of_day, query, device_type 等
// - 实时特征:realtime_ctr, realtime_exposure 等(建议加 realtime_ 前缀区分)
Params map[string]any
// contains filtered or unexported fields
}
RecommendContext 承载用户/场景/实时信息,贯穿整个 Pipeline 透传。
func (*RecommendContext) GetExtension ¶
func (rctx *RecommendContext) GetExtension(name string) (Extension, bool)
GetExtension 按名称获取已注册的 Extension。并发安全。
func (*RecommendContext) GetLabel ¶
func (rctx *RecommendContext) GetLabel(key string) (utils.Label, bool)
GetLabel 获取用户级 Label。
func (*RecommendContext) PutLabel ¶
func (rctx *RecommendContext) PutLabel(key string, lbl utils.Label)
PutLabel 写入用户级 Label。
func (*RecommendContext) SetExtension ¶
func (rctx *RecommendContext) SetExtension(e Extension)
SetExtension 注册一个 Extension 到 Context,按 ExtensionName() 索引。 rctx 或 e 为 nil 时静默忽略。并发安全。
type ScoredMember ¶
ScoredMember 表示有序集合中的成员及其分数。
type SortedSetRangeStore ¶
type SortedSetRangeStore interface {
// ZRangeWithScores 按分数升序获取有序集合成员及分数
ZRangeWithScores(ctx context.Context, key string, start, stop int64) ([]ScoredMember, error)
// ZRevRangeWithScores 按分数降序获取有序集合成员及分数
ZRevRangeWithScores(ctx context.Context, key string, start, stop int64) ([]ScoredMember, error)
}
SortedSetRangeStore 是 KeyValueStore 的可选扩展,支持带分数的有序集合查询和双向排序。
当 Store 同时实现此接口时,SortedSetRecall 等模块可获取分数并支持正/倒序查询。 未实现此接口时,降级到 KeyValueStore.ZRange(仅降序、不含分数)。
type Store ¶
type Store interface {
// Name 返回存储后端名称(用于日志/监控)
Name() string
// Get 读取单个 key 的值
Get(ctx context.Context, key string) ([]byte, error)
// Set 写入单个 key-value
Set(ctx context.Context, key string, value []byte, ttl ...int) error
// Delete 删除单个 key
Delete(ctx context.Context, key string) error
// BatchGet 批量读取(推荐系统常用,减少网络往返)
BatchGet(ctx context.Context, keys []string) (map[string][]byte, error)
// BatchSet 批量写入
BatchSet(ctx context.Context, kvs map[string][]byte, ttl ...int) error
// Close 关闭连接/释放资源
Close(ctx context.Context) error
}
Store 是存储的领域接口。
设计原则:
- 定义在领域层(core),由基础设施层(store)实现
- 遵循依赖倒置原则:领域层定义接口,基础设施层实现接口
- 避免循环依赖:领域层不依赖基础设施层
使用场景:
- 召回数据存储:协同过滤、内容推荐、矩阵分解等
- 特征存储:用户特征、物品特征
- 缓存:特征缓存、结果缓存
实现:
- store.MemoryStore 实现此接口
- store.RedisStore 实现此接口
- 其他存储后端(MySQL、ES 等)也可以实现此接口
type UserProfile ¶
type UserProfile struct {
UserID string // 使用 string 类型(通用,支持所有 ID 格式)
// 静态属性(冷启动 / 基础过滤)
Gender string // male / female / unknown
Age int // 年龄
Location string // 地理位置
// 兴趣画像(长期)- Recall / Rank 核心
// key: category/tag,value: weight (0-1)
Interests map[string]float64
// 行为统计(短期)- 实时调权
RecentClicks []string // 最近点击的物品 ID
RecentImpress []string // 最近曝光的物品 ID
// 偏好信号
PreferTags map[string]float64 // 标签偏好
// 控制与实验(策略切换)
Buckets map[string]string // AB / 实验桶,例如 {"diversity": "strong", "recall": "v2"}
// 扩展字段(用户自定义属性)
// 用于存储框架未定义的用户属性,支持任意类型
// 例如:VIP 等级、价格偏好、自定义标签等
Extras map[string]any
// 元数据
UpdateTime time.Time // 最后更新时间
}
UserProfile 是框架提供的可选用户画像参考实现。
重要说明:
- 这是一个便利工具,不是框架强制要求的类型。
- 框架内置 Node 不直接依赖此 struct,而是通过 Attributes map 或 Extractor 函数获取数据。
- 业务方可以自由使用自己的 User struct,将其放入 RecommendContext.User(any 类型), 并通过 Attributes 传递框架需要读取的数据。
- 如果使用此 struct,可将其放入 RecommendContext.User 供自定义 Node 做 type assert。
func (*UserProfile) AddRecentClick ¶
func (p *UserProfile) AddRecentClick(itemID string, maxSize int)
AddRecentClick 添加最近点击记录。
func (*UserProfile) AddRecentImpress ¶
func (p *UserProfile) AddRecentImpress(itemID string, maxSize int)
AddRecentImpress 添加最近曝光记录。
func (*UserProfile) GetBucket ¶
func (p *UserProfile) GetBucket(key string) string
GetBucket 获取实验桶值。
func (*UserProfile) GetExtra ¶
func (p *UserProfile) GetExtra(key string) (any, bool)
GetExtra 获取扩展属性(任意类型)。 用于访问用户自定义的属性,例如 VIP 等级、价格偏好等。
func (*UserProfile) GetExtraFloat64 ¶
func (p *UserProfile) GetExtraFloat64(key string) (float64, bool)
GetExtraFloat64 获取扩展属性(float64 类型)。 支持 float64、float32、int、int64、int32、bool 的自动转换。
func (*UserProfile) GetExtraInt ¶
func (p *UserProfile) GetExtraInt(key string) (int, bool)
GetExtraInt 获取扩展属性(int 类型)。 支持 int、int64、int32、float64、float32 的自动转换。
func (*UserProfile) GetExtraString ¶
func (p *UserProfile) GetExtraString(key string) (string, bool)
GetExtraString 获取扩展属性(字符串类型)。
func (*UserProfile) GetInterestWeight ¶
func (p *UserProfile) GetInterestWeight(category string) float64
GetInterestWeight 获取兴趣权重。
func (*UserProfile) HasInterest ¶
func (p *UserProfile) HasInterest(category string, threshold float64) bool
HasInterest 检查用户是否有某个兴趣。
func (*UserProfile) SetExtra ¶
func (p *UserProfile) SetExtra(key string, value any)
SetExtra 设置扩展属性(任意类型)。 用于存储用户自定义的属性,例如 VIP 等级、价格偏好等。
func (*UserProfile) UpdateInterest ¶
func (p *UserProfile) UpdateInterest(category string, weight float64)
UpdateInterest 更新用户兴趣(支持 Online Learning)。
type VectorCreateCollectionRequest ¶
type VectorCreateCollectionRequest struct {
// Name 集合名称
Name string
// Dimension 向量维度
Dimension int
// Metric 距离度量方式
Metric string
// Params 额外参数
Params map[string]interface{}
}
VectorCreateCollectionRequest 创建集合请求
type VectorDatabaseService ¶
type VectorDatabaseService interface {
// 嵌入召回场景接口(符合 DDD 原则)
// 基础设施层接口扩展领域层接口,而不是相反
VectorService
// Insert 插入向量
Insert(ctx context.Context, req *VectorInsertRequest) error
// Update 更新向量
Update(ctx context.Context, req *VectorUpdateRequest) error
// Delete 删除向量
Delete(ctx context.Context, req *VectorDeleteRequest) error
// CreateCollection 创建集合
CreateCollection(ctx context.Context, req *VectorCreateCollectionRequest) error
// DropCollection 删除集合
DropCollection(ctx context.Context, collection string) error
// HasCollection 检查集合是否存在
HasCollection(ctx context.Context, collection string) (bool, error)
}
VectorDatabaseService 是完整的向量数据库服务接口。
设计原则:
- 定义在领域层(core),由基础设施层(vector)实现
- 嵌入 VectorService(召回场景接口),符合接口组合原则
- 提供完整的向量数据库操作(CRUD + 集合管理)
使用场景对比:
召回场景(推荐使用 VectorService): ```go var vectorService VectorService = milvusService result, err := vectorService.Search(ctx, &VectorSearchRequest{ Collection: "items", Vector: userVector, TopK: 20, Metric: "cosine", }) ```
数据管理场景(使用 VectorDatabaseService): ```go var dbService VectorDatabaseService = milvusService // 创建集合 err := dbService.CreateCollection(ctx, &VectorCreateCollectionRequest{ Name: "items", Dimension: 128, Metric: "cosine", }) // 插入向量 err = dbService.Insert(ctx, &VectorInsertRequest{ Collection: "items", Vectors: itemVectors, IDs: itemIDs, }) // 也可以使用 Search(因为嵌入了 VectorService) result, err := dbService.Search(ctx, &VectorSearchRequest{...}) ```
实现:
- ext/vector/milvus.MilvusService 实现此接口(扩展包)
- store.MemoryVectorService 实现此接口(内存实现)
- 其他向量数据库(Faiss、Elasticsearch 等)也可以实现此接口
type VectorDeleteRequest ¶
type VectorDeleteRequest struct {
// Collection 集合名称
Collection string
// IDs 要删除的物品 ID 列表
IDs []string
}
VectorDeleteRequest 向量删除请求
type VectorInsertRequest ¶
type VectorInsertRequest struct {
// Collection 集合名称
Collection string
// Vectors 向量列表
Vectors [][]float64
// IDs 对应的物品 ID 列表
IDs []string
// Metadata 元数据
Metadata []map[string]interface{}
}
VectorInsertRequest 向量插入请求
type VectorSearchItem ¶
type VectorSearchItem struct {
// ID 物品 ID
ID string
// Score 相似度分数
Score float64
// Distance 距离
Distance float64
}
VectorSearchItem 单个向量搜索结果项
type VectorSearchRequest ¶
type VectorSearchRequest struct {
// Collection 集合名称
Collection string
// Vector 查询向量
Vector []float64
// TopK 返回 TopK 个最相似的结果
TopK int
// Metric 距离度量方式:cosine / euclidean / inner_product
Metric string
// Filter 过滤条件(可选)
Filter map[string]interface{}
// Params 额外参数(可选)
Params map[string]interface{}
}
VectorSearchRequest 向量搜索请求
type VectorSearchResult ¶
type VectorSearchResult struct {
// Items 搜索结果项列表(按相似度排序)
Items []VectorSearchItem
}
VectorSearchResult 向量搜索结果
type VectorService ¶
type VectorService interface {
// Search 向量搜索
Search(ctx context.Context, req *VectorSearchRequest) (*VectorSearchResult, error)
// Close 关闭连接
Close(ctx context.Context) error
}
VectorService 是向量检索服务的领域接口。
设计原则:
- 定义在领域层(core),由基础设施层(vector)实现
- 遵循依赖倒置原则:领域层定义接口,基础设施层实现接口
- 避免循环依赖:领域层不依赖基础设施层
使用场景(召回场景专用):
- 双塔模型召回:根据 User Embedding 检索 Item Embeddings
- ANN 召回:向量相似度搜索
- 其他需要向量检索的召回场景
注意:
- 此接口只包含 Search 方法,专注于召回场景
- 如果需要完整的向量数据库操作(Insert、Update、Delete 等),请使用 core.VectorDatabaseService
实现:
- ext/vector/milvus.MilvusService 实现此接口(通过 core.VectorDatabaseService)
- 其他向量数据库(Faiss、Elasticsearch 等)也可以实现此接口