🎯 概述
Upstash Vector 是无服务器向量数据库:
- 算法:DiskANN、FreshDiskANN
- 用途:RAG、语义搜索、推荐系统
- 集成:OpenAI、Cohere 嵌入模型
- 元数据:支持向量附带元数据
🚀 快速开始
安装 SDK
bash
npm install @upstash/vector
# 或
pip install upstash-vector
插入向量
javascript
import { Index } from '@upstash/vector'
const index = new Index({
url: 'UPSTASH_VECTOR_REST_URL',
token: 'UPSTASH_VECTOR_REST_TOKEN',
})
// 插入向量(文本自动嵌入)
await index.upsert([{
id: 'doc1',
data: 'Paris is the capital of France.',
metadata: { country: 'France' }
}])
// 或提供向量
await index.upsert([{
id: 'doc2',
vector: [0.1, 0.2, 0.3, ...],
metadata: { country: 'Japan' }
}])
搜索
javascript
// 文本搜索(自动嵌入)
const results = await index.query('capital city', {
topK: 5,
includeMetadata: true,
})
// 向量搜索
const results = await index.query(
[0.1, 0.2, 0.3, ...],
{ topK: 10 }
)
// 带过滤
const results = await index.query('capital', {
topK: 5,
filter: 'country = "France"',
})
📚 RAG 示例
javascript
import { Index } from '@upstash/vector'
import OpenAI from 'openai'
const index = new Index({ url, token })
const openai = new OpenAI()
// 1. 索引文档
async function indexDocument(text, id) {
await index.upsert([{
id,
data: text,
metadata: { text }
}])
}
// 2. RAG 查询
async function ragQuery(question) {
// 搜索相关文档
const results = await index.query(question, { topK: 3 })
const context = results.map(r => r.metadata?.text).join('\n\n')
// 调用 LLM
const response = await openai.chat.completions.create({
model: 'gpt-4',
messages: [
{ role: 'system', content: 'Use the context to answer.' },
{ role: 'user', content: `Context: ${context}\n\nQuestion: ${question}` }
]
})
return response.choices[0].message.content
}
🔄 CDC 管道
支持 PostgreSQL → Kafka → Vector 的 CDC 管道:
- PostgreSQL 数据变更 → Kafka 流
- Kafka → Vector 自动更新嵌入
- 实时保持 AI 系统最新