InMemoryVectorStore 内置于 rig。它将文档及其嵌入保存在 RAM 中,按余弦相似度排名,无需数据库或额外 feature。适合开发、测试和小数据集。
注意
向量存储概览介绍的共通部分(EmbeddingsBuilder、VectorSearchRequest、过滤器、trait)同样适用于这里。
快速开始#
use rig::prelude::*;
use serde::{Deserialize, Serialize};
use rig::providers::openai::{self, OpenAI};
#[derive(Embed, Clone, Serialize, Deserialize, Debug)]
struct WordDefinition {
id: String,
#[embed]
definition: String,
}
#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
let model = OpenAI::from_env()?.embedding(openai::TEXT_EMBEDDING_3_SMALL, None);
let documents = vec![
WordDefinition { id: "doc0".into(), definition: "First document content".into() },
WordDefinition { id: "doc1".into(), definition: "Second document content".into() },
];
let embeddings = EmbeddingsBuilder::new(model.clone())
.documents(documents)?
.build()
.await?;
// Build the store, then an index that embeds queries with the same model.
let index = InMemoryVectorStore::from_documents(embeddings).index(model);
let req = VectorSearchRequest::builder()
.query("search query")
.samples(5)
.build();
for result in index.top_n::<WordDefinition>(req).await? {
println!("{:.3} {} {:?}", result.score, result.id, result.document);
}
Ok(())
}InMemoryVectorStore<D> 保存数据;.index(model) 将其转换为 InMemoryVectorIndex<D>。后者实现 VectorStoreIndex,并用 model 为每次查询生成嵌入。应使用为文档生成嵌入的同一个模型。
添加文档#
存储将字符串 ID 映射到文档及其嵌入。三种构造函数都能填充数据,区别在于如何选择 ID:
use rig::embeddings::Embedding;
#[derive(Serialize, Clone)]
struct WordDefinition { id: String }
let doc = |id: &str| (WordDefinition { id: id.into() }, vec![Embedding::default()]);
// 1. Generated ids: "doc0", "doc1", ...
let store = InMemoryVectorStore::from_documents(vec![doc("a"), doc("b")]);
// 2. Explicit ids
let store = InMemoryVectorStore::from_documents_with_ids(vec![
("custom_id_1", doc("a").0, doc("a").1),
("custom_id_2", doc("b").0, doc("b").1),
]);
// 3. Ids derived from each document
let store = InMemoryVectorStore::from_documents_with_id_f(
vec![doc("a"), doc("b")],
|d| format!("word:{}", d.id),
);每一对都是 (document, Vec<Embedding>),正好对应 EmbeddingsBuilder::build() 的返回值。要向现有存储增加数据,使用相应的 add_documents、add_documents_with_ids 和 add_documents_with_id_f 方法。add_documents 永远不会覆盖已有 ID;另外两个方法会替换 ID 已存在的文档。
搜索策略#
默认情况下,查询会扫描每个文档(暴力搜索)。数据量较大时,使用局部敏感哈希(LSH)进行近似搜索,可以先将扫描范围缩小到可能的候选项,再精确计算得分。通过构建器选择:
use rig::embeddings::Embedding;
use rig::vector_store::IndexStrategy;
let store = InMemoryVectorStore::builder()
.index_strategy(IndexStrategy::LSH { num_tables: 8, num_hyperplanes: 16 })
.documents(embeddings)
.build();带多个嵌入的文档按其中最佳匹配进行排名。过滤器和阈值在扫描期间应用,然后才选出排名靠前的结果。
过滤#
内存存储使用与后端无关的 Filter,根据每个文档的 JSON 形式进行匹配:
use rig::vector_store::request::{Filter, SearchFilter};
let req = VectorSearchRequest::builder()
.query("search query")
.samples(5)
.filter(Filter::eq("category", json!("science")))
.build();在 Agent 中使用#
内存索引可以作为 Agent 工具(.tool(index)),也可以在每次发送提示词时进行检索(.dynamic_context(n, index)):
use rig::prelude::*;
use rig::providers::openai::{self, OpenAI};
let client = OpenAI::from_env()?;
let model = client.embedding(openai::TEXT_EMBEDDING_3_SMALL, None);
let index = InMemoryVectorStore::<String>::default().index(model);
let agent = AgentBuilder::new(client.completion(openai::GPT_5_5))
.preamble("Answer using the retrieved documents.")
.dynamic_context(2, index)
.build();注意事项#
- 内存:所有文档和嵌入都在 RAM 中,内存使用量随文档数和向量维度增长。
- 持久化:不提供。每次运行时重新构建存储,或改用数据库存储。
- 共享:
InMemoryVectorStore实现了Clone、Send和Sync。.index(model)会消耗存储,因此应在创建索引前添加文档。
如果需要持久化、更大数据集或服务端过滤,可改用数据库存储;嵌入与查询代码保持不变。