VectorStore(向量数据库/向量存储)是一种专门用于存储和检索向量嵌入(Vector Embeddings)的数据库。它是实现 RAG(Retrieval-Augmented Generation,检索增强生成) 技术的核心组件。
为什么需要 VectorStore?
在传统的 AI 应用中,大语言模型(LLM)只能基于训练数据回答问题。但存在两个问题:
-
知识截止:模型不知道训练后的新信息
-
私有数据:模型无法访问企业的内部数据
VectorStore 解决了这个问题:
用户提问 → 检索相关文档 → 注入上下文 → LLM 生成回答
VectorStore的工作原理是向量嵌入,把文本/对象转换为数值数组,通过计算向量间的距离来找到最相似的内容。
Spring AI Dependencies
dependencies {
// PGVector (PostgreSQL)
implementation 'org.springframework.ai:spring-ai-pgvector-store-spring-boot-starter'
implementation 'org.springframework.ai:spring-ai-vector-store-advisor'
// Redis
implementation 'org.springframework.ai:spring-ai-redis-store-spring-boot-starter'
// 内存存储(测试用)
implementation 'org.springframework.ai:spring-ai-inmemory-store-spring-boot-starter'
// Embedding 模型
implementation 'org.springframework.ai:spring-ai-openai-spring-boot-starter'
}
核心操作
@Service
public class VectorStoreService {
@Autowired
private VectorStore vectorStore;
public void addDocuments() {
// 方式1:纯文本
Document doc1 = new Document("这是一只可爱的金毛犬");
// 方式2:带元数据
Document doc2 = new Document(
"神经质的狗,不喜欢小孩和动物",
Map.of(
"id", 45,
"name", "Prancer",
"type", "dog"
)
);
vectorStore.add(List.of(doc1, doc2));
}
}
常见问题与解决方案
VectorStore 数据没有更新
问题:修改代码后,查询结果不变
原因:VectorStore 是持久化存储,数据已存入数据库
解决:
sql
-- 清空表重新加载 TRUNCATE vector_store;

322

被折叠的 条评论
为什么被折叠?



