Ruby 中用于向量数据库的 Rack 风格中间件:vectra-client 1.1.0
I’m happy to translate the article for you, but I’ll need the full text of the post (the content you’d like translated). Could you please paste the article’s body here? I’ll keep the source line and all formatting exactly as you requested.
Introduction
如果你在 Ruby 中构建严肃的 AI 功能(语义搜索、检索增强生成(RAG)、推荐系统),你会很快意识到,你不仅仅需要一个向量数据库的客户端——你还需要一个生产级工具箱。
使用 vectra-client 1.1.0,该 gem 为向量数据库提供了类似 Rack 的中间件,以及 Ruby/Rails 开发者已经熟悉的生产模式。
核心特性
- 生产模式:7+ 内置模式(批量 upsert、健康检查、ActiveRecord 集成、重新索引、缓存,…)
- 中间件:5 个内置中间件(唯一采用此方式的 gem)
- 多提供商:统一 API,支持
:pinecone、:qdrant、:weaviate、:pgvector和:memory
“唯一提供 Rack 风格中间件的 Ruby gem,用于向量数据库——你已经熟悉的生产模式,应用于 AI 工作负载。”
所有对 Vectra::Client 的公开操作现在都通过中间件栈进行(upsert、query、fetch、update、delete、list_indexes、describe_index、stats、create_index、delete_index、list_namespaces)。
这带来了什么
- 在全局添加日志记录 / 重试 / 监控
- 为每个客户端添加中间件(例如,仅对特定索引进行个人身份信息(PII)脱敏)
使用示例
require "vectra-client"
# Global middleware
Vectra::Client.use Vectra::Middleware::Logging
Vectra::Client.use Vectra::Middleware::Retry, max_attempts: 3
Vectra::Client.use Vectra::Middleware::CostTracker
client = Vectra::Client.new(
provider: :qdrant,
index: "products",
namespace: "tenant-1",
middleware: [
Vectra::Middleware::PIIRedaction,
Vectra::Middleware::Instrumentation
]
)
# Every call (client.upsert, client.query, …) now flows through the same pipeline.
内置中间件 (v1.1.0)
| Middleware | Purpose |
|---|---|
Logging | 对所有操作进行结构化日志记录 + 以毫秒为单位的持续时间 |
Retry | 针对速率限制、网络或超时错误的重试逻辑 |
Instrumentation | 用于指标和 APM(Datadog、New Relic、Prometheus 等)的钩子 |
PIIRedaction | 在发送到向量数据库之前对元数据中的个人身份信息进行脱敏 |
CostTracker | 对每次操作的成本进行简单估算(按提供商、按向量) |
辅助方法
client.with_index("shadow-products") do |ctx|
ctx.upsert(vectors: batch)
end
client.with_namespace("tenant-42") do |ctx|
ctx.query(vector: embedding, top_k: 10)
end
client.with_index_and_namespace("products", "tenant-1") do |ctx|
ctx.delete(ids: ["products_123"])
end
这些辅助方法简化了多租户设置、影子索引、迁移和 A/B 测试。
安装
-
将 gem 添加到你的 Gemfile
gem "vectra-client" -
运行安装生成器
rails generate vectra:install -
为你的模型生成索引(例如
Product)rails generate vectra:index Product embedding dimension:1536 provider:qdrant -
包含生成的 concern 并使用帮助方法
class Product < ApplicationRecord include ProductVector end- 保存后自动索引嵌入
- 通过
Product.vector_search(...)执行语义搜索 - 通过
Product.reindex_vectors重新索引整个表
何时使用 vectra-client 合适?
如果你正在构建以下任意项目,生产特性(中间件、健康检查、批处理、重新索引、供应商无关 API)就变得必不可少:
- 电子商务搜索(语义 + 过滤)
- 博客 / 文档搜索(混合:关键字 + 向量)
- 从 PostgreSQL + pgvector 拉取上下文的 RAG 聊天机器人
- 多租户 SaaS,具备命名空间隔离
- 推荐系统(相似商品 / 文章)
摘要
Ruby 生态系统现在拥有一套严肃、可用于生产的向量数据库工具包:
- 您已经熟悉的 Rack 风格中间件
- 将生产模式映射到 AI 工作负载
- 多供应商 API,避免锁定单一供应商
资源
- 文档首页: https://github.com/stokry/vectra#readme
- 中间件指南: https://github.com/stokry/vectra/wiki/Middleware-Guide
- 示例概览: https://github.com/stokry/vectra/tree/main/examples
如果您想要特定技术栈(Sidekiq、Hanami、dry‑rb 等)的示例,请在仓库中打开 issue。
GitHub 仓库: https://github.com/stokry/vectra