跳到主要内容
版本:2.0.1

向量数据库

QWen 3.8 中英对照 Vector Databases

向量数据库是一种专门的数据库类型,在 AI 应用中发挥着至关重要的作用。

在向量数据库中,查询与传统关系型数据库有所不同。它们不执行精确匹配,而是进行相似度搜索。当给定一个向量作为查询时,向量数据库会返回与查询向量“相似”的向量。有关相似度在高层面上如何计算的更多细节,请参考Vector Similarity。

向量数据库用于将你的数据与 AI 模型集成。使用向量数据库的第一步是将数据加载到向量数据库中。随后,当用户查询需要发送给 AI 模型时,会先检索一组相似的文档。这些文档作为用户问题的上下文,连同用户查询一起发送给 AI 模型。这种技术被称为 检索增强生成 (RAG)。

以下各节介绍了 Spring AI 接口,用于使用多种向量数据库实现,并提供了部分高层级的使用示例。

最后一部分旨在阐明向量数据库中相似性搜索的底层方法。

API 概览​

本节作为 Spring AI 框架中 VectorStore 接口及其关联类的使用指南。

Spring AI 通过 VectorStore 接口及其只读对应的 VectorStoreRetriever 接口,提供了与向量数据库进行交互的抽象 API。

VectorStoreRetriever 接口​

Spring AI 提供了一个名为 VectorStoreRetriever 的只读接口,该接口仅暴露文档检索功能:

@FunctionalInterface
public interface VectorStoreRetriever {

List<Document> similaritySearch(SearchRequest request);

default List<Document> similaritySearch(String query) {
return this.similaritySearch(SearchRequest.builder().query(query).build());
}
}

此函数式接口专为仅需要从向量存储中检索文档而不执行任何变更操作的场景而设计。它遵循最小权限原则,仅暴露文档检索所需的必要功能。

VectorStore 接口​

VectorStore 接口继承自 VectorStoreRetriever,并增加了修改功能:

public interface VectorStore extends DocumentWriter, VectorStoreRetriever {

default String getName() {
return this.getClass().getSimpleName();
}

void add(List<Document> documents);

void delete(List<String> idList);

void delete(Filter.Expression filterExpression);

default void delete(String filterExpression) { ... }

default <T> Optional<T> getNativeClient() {
return Optional.empty();
}
}

VectorStore 接口同时结合了读和写操作,允许你在向量数据库中添加、删除和搜索文档。

SearchRequest Builder​

public class SearchRequest {

public static final double SIMILARITY_THRESHOLD_ACCEPT_ALL = 0.0;

public static final int DEFAULT_TOP_K = 4;

private String query = "";

private int topK = DEFAULT_TOP_K;

private double similarityThreshold = SIMILARITY_THRESHOLD_ACCEPT_ALL;

@Nullable
private Filter.Expression filterExpression;

public static Builder from(SearchRequest originalSearchRequest) {
return builder().query(originalSearchRequest.getQuery())
.topK(originalSearchRequest.getTopK())
.similarityThreshold(originalSearchRequest.getSimilarityThreshold())
.filterExpression(originalSearchRequest.getFilterExpression());
}

public static class Builder {

private final SearchRequest searchRequest = new SearchRequest();

public Builder query(String query) {
Assert.notNull(query, "Query can not be null.");
this.searchRequest.query = query;
return this;
}

public Builder topK(int topK) {
Assert.isTrue(topK >= 0, "TopK should be positive.");
this.searchRequest.topK = topK;
return this;
}

public Builder similarityThreshold(double threshold) {
Assert.isTrue(threshold >= 0 && threshold <= 1, "Similarity threshold must be in [0,1] range.");
this.searchRequest.similarityThreshold = threshold;
return this;
}

public Builder similarityThresholdAll() {
this.searchRequest.similarityThreshold = 0.0;
return this;
}

public Builder filterExpression(@Nullable Filter.Expression expression) {
this.searchRequest.filterExpression = expression;
return this;
}

public Builder filterExpression(@Nullable String textExpression) {
this.searchRequest.filterExpression = (textExpression != null)
? new FilterExpressionTextParser().parse(textExpression) : null;
return this;
}

public SearchRequest build() {
return this.searchRequest;
}

}

public String getQuery() {...}
public int getTopK() {...}
public double getSimilarityThreshold() {...}
public Filter.Expression getFilterExpression() {...}
}

要将数据插入向量数据库,需将其封装在 Document 对象中。Document 类用于封装来自数据源(如 PDF 或 Word 文档)的内容,并以字符串形式表示文本。此外,它还包含以键值对形式存在的元数据,包括文件名等详细信息。

插入向量数据库时,文本内容会通过嵌入模型被转换为数值数组,即 float[],也就是向量嵌入(vector embeddings)。嵌入模型(如 Word2Vec、GLoVE、BERT,或 OpenAI 的 text-embedding-ada-002)用于将单词、句子或段落转换为这些向量嵌入。

向量数据库的作用是存储这些嵌入并促进相似性搜索。它本身并不生成嵌入。若要创建向量嵌入,应使用 EmbeddingModel。

接口中的 similaritySearch 方法允许检索与给定查询字符串相似的文档。可以使用以下参数对这些方法进行微调:

  • k:一个整数,指定要返回的最多相似文档数量。这通常被称为“Top K”搜索或“K 近邻”(KNN)搜索。

  • threshold:一个取值范围在 0 到 1 之间的 double 值,越接近 1 表示相似度越高。例如,默认情况下,如果您将阈值设置为 0.75,则仅返回相似度高于该值的文档。

  • Filter.Expression:一个用于传递流式 DSL(Domain-Specific Language,领域特定语言)表达式的类,其功能类似于 SQL 中的 'where' 子句,但它仅应用于 Document 的元数据键值对。

  • filterExpression:一种基于 ANTLR4 的外部 DSL,接受字符串形式的过滤表达式。例如,如果元数据键包含 country、year 和 isActive,您可以使用如下表达式:country == 'UK' && year >= 2020 && isActive == true.

有关 Filter.Expression 的详细信息,请参见 元数据过滤器 部分。

Schema 初始化​

某些向量存储要求在使用前初始化其后端模式(schema)。默认情况下,系统不会自动为您完成初始化。您必须通过显式传入 boolean 类型的相应构造参数来启用此功能;或者,如果您使用的是 Spring Boot,则需在 application.properties 或 application.yml 中将相应的 initialize-schema 属性设置为 true。请查阅您所使用的向量存储文档,以获取具体的属性名称。

批处理策略​

在使用向量存储时,通常需要嵌入大量文档。虽然一次性调用嵌入所有文档看似简单直接,但这种做法可能会引发问题。嵌入模型以 token 为单位处理文本,并存在最大 token 限制,通常称为上下文窗口大小。该限制约束了单次嵌入请求中可处理的文本量。在一次调用中尝试嵌入过多的 token 可能会导致错误或被截断的嵌入结果。

为解决该 token 限制问题,Spring AI 实现了批处理策略。该方法将大型文档集合拆分为可适配嵌入模型最大上下文窗口的更小的批次。批处理不仅解决了 token 限制问题,还能提升性能并更高效地利用 API 速率限制。

Spring AI 通过 BatchingStrategy 接口提供此功能,该接口允许根据文档的 token 数量将文档划分为子批次进行处理。

核心 BatchingStrategy 接口定义如下:

public interface BatchingStrategy {
List<List<Document>> batch(List<Document> documents);
}

该接口定义了一个方法 batch,该方法接收一个文档列表,并返回一个文档批次列表。

默认实现​

Spring AI 提供了一个名为 TokenCountBatchingStrategy 的默认实现。该策略基于文档的 Token 数量进行批量处理,确保每个批次不超过计算得出的最大输入 Token 数。

TokenCountBatchingStrategy 的关键特性:

  1. 使用 OpenAI 的最大输入 token 数量(8191)作为默认上限。

  2. 引入保留百分比(默认 10%),以预留潜在开销的缓冲空间。

  3. 计算实际的 max input token count 为:actualMaxInputTokenCount = originalMaxInputTokenCount * (1 - RESERVE_PERCENTAGE)

该策略会估算每个文档的 token 数量,将它们分组为批次,确保不超过最大输入 token 数量,如果单个文档超过此限制,则抛出异常。

你还可以自定义 TokenCountBatchingStrategy 以更好地满足你的特定需求。这可以通过在 Spring Boot 的 @Configuration 类中创建带有自定义参数的新实例来实现。

以下是一个创建自定义 TokenCountBatchingStrategy bean 的示例:

@Configuration
public class EmbeddingConfig {
@Bean
public BatchingStrategy customTokenCountBatchingStrategy() {
return new TokenCountBatchingStrategy(
EncodingType.CL100K_BASE, // Specify the encoding type
8000, // Set the maximum input token count
0.1 // Set the reserve percentage
);
}
}

在此配置中:

  1. EncodingType.CL100K_BASE:指定用于分词的编码类型。JTokkitTokenCountEstimator 使用此编码类型来准确估算 token 数量。

  2. 8000:设置最大输入 token 数量。该值应小于或等于嵌入模型的最大上下文窗口大小。

  3. 0.1:设置预留百分比。即从最大输入 token 数量中预留的百分比。这为处理过程中可能出现的 token 数量增加提供了缓冲。

默认情况下,此构造函数使用 Document.DEFAULT_CONTENT_FORMATTER 进行内容格式化,并使用 MetadataMode.NONE 处理元数据。如果需要自定义这些参数,可以使用带额外参数的完整构造函数。

定义完成后,此自定义的 TokenCountBatchingStrategy bean 将自动被应用程序中的 EmbeddingModel 实现类使用,以替代默认策略。

TokenCountBatchingStrategy 内部使用 TokenCountEstimator(具体为 JTokkitTokenCountEstimator)来计算 token 数量,以实现高效的批量处理。这确保了基于指定编码类型的准确 token 估算。

此外,TokenCountBatchingStrategy 通过允许传入 TokenCountEstimator 接口的自定义实现来提供灵活性。此功能使您能够使用针对特定需求定制的令牌计数策略。例如:

TokenCountEstimator customEstimator = new YourCustomTokenCountEstimator();
TokenCountBatchingStrategy strategy = new TokenCountBatchingStrategy(
this.customEstimator,
8000, // maxInputTokenCount
0.1, // reservePercentage
Document.DEFAULT_CONTENT_FORMATTER,
MetadataMode.NONE
);

自动截断​

部分嵌入模型(例如 Vertex AI 文本嵌入模型)支持 auto_truncate 功能。启用后,模型会静默截断超出最大尺寸的文本输入并继续处理;禁用后,对于过大的输入则会抛出明确的错误。

当使用自动截断与批处理策略时,必须将批处理策略的输入 token 数配置得远高于模型实际的最大值。这可以防止批处理策略对大型文档抛出异常,从而允许嵌入模型在内部处理截断。

自动截断配置​

启用自动截断时,将批处理策略的最大输入 Token 数设置为远高于模型的实际限制值。这可防止批处理策略因处理大型文档而抛出异常,从而允许嵌入模型在内部处理截断。

以下是一个使用 Vertex AI 并启用自动截断及自定义 BatchingStrategy 的示例配置,随后在 PgVectorStore 中使用它们:

@Configuration
public class AutoTruncationEmbeddingConfig {

@Bean
public VertexAiTextEmbeddingModel vertexAiEmbeddingModel(
VertexAiEmbeddingConnectionDetails connectionDetails) {

VertexAiTextEmbeddingOptions options = VertexAiTextEmbeddingOptions.builder()
.model(VertexAiTextEmbeddingOptions.DEFAULT_MODEL_NAME)
.autoTruncate(true) // Enable auto-truncation
.build();

return new VertexAiTextEmbeddingModel(connectionDetails, options);
}

@Bean
public BatchingStrategy batchingStrategy() {
// Only use a high token limit if auto-truncation is enabled in your embedding model.
// Set a much higher token count than the model actually supports
// (e.g., 132,900 when Vertex AI supports only up to 20,000)
return new TokenCountBatchingStrategy(
EncodingType.CL100K_BASE,
132900, // Artificially high limit
0.1 // 10% reserve
);
}

@Bean
public VectorStore vectorStore(JdbcTemplate jdbcTemplate, EmbeddingModel embeddingModel, BatchingStrategy batchingStrategy) {
return PgVectorStore.builder(jdbcTemplate, embeddingModel)
// other properties omitted here
.build();
}
}

在此配置中:

  1. 嵌入模型已启用自动截断功能,能够优雅地处理超出限制大小的输入。

  2. 批量处理策略使用了一个人为设置的较高令牌限制(132,900),该限制远大于实际的模型限制(20,000)。

  3. 向量存储使用配置的嵌入模型和自定义的 BatchingStrategy Bean。

为什么有效​

这种方法有效,原因是:

  1. TokenCountBatchingStrategy 会检查是否有单个文档超过了配置的最大值,如果超过,则抛出 IllegalArgumentException。

  2. 通过在批处理策略中设置一个非常高的限制,我们确保此检查永远不会失败。

  3. 超过模型限制的文档或批次会被静默截断,并由嵌入模型的自动截断功能处理。

最佳实践​

使用自动截断时:

  • 将批处理策略的最大输入 token 数设置为至少是模型实际限制的 5-10 倍,以避免批处理策略过早抛出异常。

  • 监控日志,查找嵌入模型发出的截断警告(注意:并非所有模型都会记录截断事件)。

  • 考虑静默截断对嵌入质量的影响。

  • 使用示例文档进行测试,以确保被截断的嵌入仍满足您的需求。

  • 将此配置记录下来以供未来的维护者参考,因为这是一种非标准配置。

警告

尽管自动截断可以防止错误,但可能会导致嵌入不完整。长文档末尾的重要信息可能会丢失。如果你的应用程序要求所有内容都被嵌入,请在嵌入前将文档拆分为更小的块。

Spring Boot 自动配置​

如果你正在使用 Spring Boot 自动配置,则必须提供一个自定义的 BatchingStrategy bean,以覆盖 Spring AI 中自带的默认策略:

@Bean
public BatchingStrategy customBatchingStrategy() {
// This bean will override the default BatchingStrategy
return new TokenCountBatchingStrategy(
EncodingType.CL100K_BASE,
132900, // Much higher than model's actual limit
0.1
);
}

在您的应用程序上下文中,此 Bean 的存在将自动替换所有向量存储使用的默认批处理策略。

自定义实现​

虽然 TokenCountBatchingStrategy 提供了稳健的默认实现,但你可以通过 Spring Boot 的自动配置来自定义批处理策略,以满足你的特定需求。

要自定义批处理策略,请在您的 Spring Boot 应用中定义一个 BatchingStrategy Bean:

@Configuration
public class EmbeddingConfig {
@Bean
public BatchingStrategy customBatchingStrategy() {
return new CustomBatchingStrategy();
}
}

此自定义的 BatchingStrategy 随后将被应用程序中的 EmbeddingModel 实现自动使用。

备注

Spring AI 支持的向量存储默认配置为使用 TokenCountBatchingStrategy。

VectorStore 实现​

以下是 VectorStore 接口现有的可用实现:

备注

Azure Cosmos DB 向量存储支持由 Azure Cosmos DB 团队维护,以外部模块的形式提供。有关更多信息,请参阅 azurecosmosdb.github.io/spring-ai/docs/index.html。

注意

SimpleVectorStore 实现并非为生产环境设计,仅应用于测试或演示用途。

未来版本中可能会支持更多实现。

如果您有一个需要由 Spring AI 支持的向量数据库,请在 GitHub 上提交 issue,或者更好的做法是提交一个包含实现的 pull request。

关于每个 VectorStore 实现的详细信息,可在本章的小节中找到。

使用示例​

要为向量数据库计算嵌入,你需要选择一个与所使用的更高级 AI 模型相匹配的嵌入模型。

例如,在使用 OpenAI 的 ChatGPT 时,我们使用 OpenAiEmbeddingModel 以及名为 text-embedding-ada-002 的模型。

Spring Boot starter 针对 OpenAI 的自动配置功能会在 Spring 应用上下文中提供一个 EmbeddingModel 实现,以便进行依赖注入。

向向量存储写入​

在向量存储中加载数据的一般用法是在类似批处理的任务中执行,首先将数据加载到 Spring AI 的 Document 类中,然后调用 VectorStore 接口上的 add 方法。

给定一个指向源文件的 String 引用,该文件表示一个包含我们要加载到向量数据库中的数据的 JSON 文件,我们使用 Spring AI 的 JsonReader 来加载 JSON 中的特定字段,将其拆分为小的片段,然后将这些小的片段传递给向量存储实现。VectorStore 实现会计算嵌入向量,并将 JSON 数据和嵌入向量存储在向量数据库中:

@Autowired
VectorStore vectorStore;

void load(String sourceFile) {
JsonReader jsonReader = new JsonReader(new FileSystemResource(sourceFile),
"price", "name", "shortDescription", "description", "tags");
List<Document> documents = jsonReader.get();
this.vectorStore.add(documents);
}

从向量存储中读取​

之后,当用户的问题被传入 AI 模型时,会执行相似度搜索以检索相似的文档,然后将这些文档作为上下文“塞入”提示词中,以支持对用户问题的回答。

对于只读操作,你可以使用 VectorStore 接口,也可以使用更为专注的 VectorStoreRetriever 接口:

@Autowired
VectorStoreRetriever retriever; // Could also use VectorStore here

String question = "<question from user>";
List<Document> similarDocuments = retriever.similaritySearch(question);

// Or with more specific search parameters
SearchRequest request = SearchRequest.builder()
.query(question)
.topK(5) // Return top 5 results
.similarityThreshold(0.7) // Only return results with similarity score >= 0.7
.build();

List<Document> filteredDocuments = retriever.similaritySearch(request);

可以通过向 similaritySearch 方法传递额外的选项,来定义要检索的文档数量以及相似度搜索的阈值。

读写操作分离​

使用独立的接口可以清晰地定义哪些组件需要写入权限,哪些组件只需要读取权限:

// Write operations in a service that needs full access
@Service
class DocumentIndexer {
private final VectorStore vectorStore;

DocumentIndexer(VectorStore vectorStore) {
this.vectorStore = vectorStore;
}

public void indexDocuments(List<Document> documents) {
vectorStore.add(documents);
}
}

// Read-only operations in a service that only needs retrieval
@Service
class DocumentRetriever {
private final VectorStoreRetriever retriever;

DocumentRetriever(VectorStoreRetriever retriever) {
this.retriever = retriever;
}

public List<Document> findSimilar(String query) {
return retriever.similaritySearch(query);
}
}

这种关注点分离有助于创建更具可维护性和安全性的应用程序,通过将变更(mutation)操作的访问权限仅限于真正需要它们的组件来实现。

使用 VectorStoreRetriever 的检索操作​

VectorStoreRetriever 接口提供向量存储的只读视图,仅暴露相似度搜索功能。这遵循最小权限原则,在 RAG(Retrieval-Augmented Generation)应用中尤为有用,在这些场景中你只需检索文档而无需修改底层数据。

使用 VectorStoreRetriever 的优势​

  1. 关注点分离:清晰地分离了读操作和写操作。

  2. 接口隔离:仅需要检索功能的客户端不会接触到变更方法。

  3. 函数式接口:对于简单的用例,可以通过 lambda 表达式或方法引用来实现。

  4. 减少依赖:仅需执行搜索操作的组件无需依赖完整的 VectorStore 接口。

使用示例​

如果你只需要执行相似度搜索,可以直接使用 VectorStoreRetriever:

@Service
public class DocumentRetrievalService {

private final VectorStoreRetriever retriever;

public DocumentRetrievalService(VectorStoreRetriever retriever) {
this.retriever = retriever;
}

public List<Document> findSimilarDocuments(String query) {
return retriever.similaritySearch(query);
}

public List<Document> findSimilarDocumentsWithFilters(String query, String country) {
SearchRequest request = SearchRequest.builder()
.query(query)
.topK(5)
.filterExpression("country == '" + country + "'")
.build();

return retriever.similaritySearch(request);
}
}

在本示例中,该服务仅依赖于 VectorStoreRetriever 接口,表明其仅执行检索操作,不会对向量存储进行修改。

与 RAG 应用的集成​

VectorStoreRetriever 接口在 RAG 应用中尤为实用,因为你需要检索相关文档以为 AI 模型提供上下文:

@Service
public class RagService {

private final VectorStoreRetriever retriever;
private final ChatModel chatModel;

public RagService(VectorStoreRetriever retriever, ChatModel chatModel) {
this.retriever = retriever;
this.chatModel = chatModel;
}

public String generateResponse(String userQuery) {
// Retrieve relevant documents
List<Document> relevantDocs = retriever.similaritySearch(userQuery);

// Extract content from documents to use as context
String context = relevantDocs.stream()
.map(Document::getContent)
.collect(Collectors.joining("\n\n"));

// Generate response using the retrieved context
String prompt = "Context information:\n" + context + "\n\nUser query: " + userQuery;
return chatModel.generate(prompt);
}
}

此模式在 RAG 应用中实现了检索组件与生成组件之间的清晰分离。

元数据过滤器​

本节介绍您可以针对查询结果使用的各种过滤器。

过滤字符串​

你可以将一个 SQL 风格的过滤表达式作为 String 传递给 similaritySearch 的某个重载。

考虑以下示例:

  • "country == 'BG'"

  • "genre == 'drama' && year >= 2020"

  • "genre in ['comedy', 'documentary', 'drama']"

Filter.Expression​

可以使用 FilterExpressionBuilder 创建 Filter.Expression 实例,该构建器提供了一个流式 API。一个简单的示例如下:

FilterExpressionBuilder b = new FilterExpressionBuilder();
Expression expression = this.b.eq("country", "BG").build();

您可以使用以下运算符构建复杂的表达式:

EQUALS: '=='
MINUS : '-'
PLUS: '+'
GT: '>'
GE: '>='
LT: '<'
LE: '<='
NE: '!='

可以使用以下运算符来组合表达式:

AND: 'AND' | 'and' | '&&';
OR: 'OR' | 'or' | '||';

考虑以下示例:

Expression exp = b.and(b.eq("genre", "drama"), b.gte("year", 2020)).build();

您还可以使用以下运算符:

IN: 'IN' | 'in';
NIN: 'NIN' | 'nin';
NOT: 'NOT' | 'not';

考虑以下示例:

Expression exp = b.and(b.in("genre", "drama", "documentary"), b.not(b.lt("year", 2020))).build();

您还可以使用以下运算符:

IS: 'IS' | 'is';
NULL: 'NULL' | 'null';
NOT NULL: 'NOT NULL' | 'not null';

考虑以下示例:

Expression exp = b.and(b.isNull("year")).build();
Expression exp = b.and(b.isNotNull("year")).build();
备注

IS NULL 和 IS NOT NULL 尚未在所有向量存储中实现。

分区共享索引​

单个向量存储(vector store)通常被多个逻辑文档组共享——例如,一个索引中可能包含多个客户、项目或知识库的内容。VectorStore 针对整个索引进行操作,并根据相似度和您提供的过滤条件返回或删除文档,因此过滤表达式用于选择您希望处理的文档组。

该方法是在写入时为每个文档打上标识其所属组的元数据标签,然后在搜索和删除时应用相应的过滤条件:

// When writing, record the group the document belongs to.
Document document = new Document(content, Map.of("group", groupId));
vectorStore.add(List.of(document));

// When searching, select documents from that group.
List<Document> results = vectorStore.similaritySearch(SearchRequest.builder()
.query(query)
.filterExpression("group == '" + groupId + "'")
.build());

// When deleting by filter, target the same group.
Filter.Expression scoped = new FilterExpressionBuilder().eq("group", groupId).build();
vectorStore.delete(scoped);

一些做法可以保证这些组之间保持清晰的分离:

  • 在写入时,为每个文档添加标识元数据,以便后续始终可用于过滤。

  • 在搜索和删除时一致地应用对应的过滤器,确保操作仅影响目标分组。

从向量存储中删除文档​

Vector Store 接口提供多种删除文档的方法,允许你通过特定的文档 ID 或使用过滤表达式来删除数据。

按文档 ID 删除​

删除文档最简单的方式是提供一个文档 ID 列表:

void delete(List<String> idList);

该方法会删除所有 ID 与所提供列表中匹配的文档。如果列表中的某个 ID 在存储中不存在,则会被忽略。

// Create and add document
Document document = new Document("The World is Big",
Map.of("country", "Netherlands"));
vectorStore.add(List.of(document));

// Delete document by ID
vectorStore.delete(List.of(document.getId()));

通过过滤表达式删除​

对于更复杂的删除条件,你可以使用过滤表达式:

void delete(Filter.Expression filterExpression);

此方法接受一个 Filter.Expression 对象,用于定义应删除哪些文档的条件。当您需要根据元数据属性删除文档时,它尤其有用。

// Create test documents with different metadata
Document bgDocument = new Document("The World is Big",
Map.of("country", "Bulgaria"));
Document nlDocument = new Document("The World is Big",
Map.of("country", "Netherlands"));

// Add documents to the store
vectorStore.add(List.of(bgDocument, nlDocument));

// Delete documents from Bulgaria using filter expression
Filter.Expression filterExpression = new Filter.Expression(
Filter.ExpressionType.EQ,
new Filter.Key("country"),
new Filter.Value("Bulgaria")
);
vectorStore.delete(filterExpression);

// Verify deletion with search
SearchRequest request = SearchRequest.builder()
.query("World")
.filterExpression("country == 'Bulgaria'")
.build();
List<Document> results = vectorStore.similaritySearch(request);
// results will be empty as Bulgarian document was deleted

按字符串过滤表达式删除​

为了方便,您还可以使用基于字符串的过滤表达式删除文档:

void delete(String filterExpression);

此方法在内部会将提供的字符串过滤器转换为 Filter.Expression 对象。当您以字符串形式提供过滤条件时,此方法非常有用。

// Create and add documents
Document bgDocument = new Document("The World is Big",
Map.of("country", "Bulgaria"));
Document nlDocument = new Document("The World is Big",
Map.of("country", "Netherlands"));
vectorStore.add(List.of(bgDocument, nlDocument));

// Delete Bulgarian documents using string filter
vectorStore.delete("country == 'Bulgaria'");

// Verify remaining documents
SearchRequest request = SearchRequest.builder()
.query("World")
.topK(5)
.build();
List<Document> results = vectorStore.similaritySearch(request);
// results will only contain the Netherlands document

调用删除 API 时的错误处理​

所有删除方法在出现错误时可能会抛出异常:

最佳实践是使用 try-catch 块包裹 delete 操作:

try {
vectorStore.delete("country == 'Bulgaria'");
}
catch (Exception e) {
logger.error("Invalid filter expression", e);
}

文档版本管理用例​

一个常见的场景是管理文档版本,你需要上传文档的新版本同时移除旧版本。以下是如何使用过滤表达式来处理此操作:

// Create initial document (v1) with version metadata
Document documentV1 = new Document(
"AI and Machine Learning Best Practices",
Map.of(
"docId", "AIML-001",
"version", "1.0",
"lastUpdated", "2024-01-01"
)
);

// Add v1 to the vector store
vectorStore.add(List.of(documentV1));

// Create updated version (v2) of the same document
Document documentV2 = new Document(
"AI and Machine Learning Best Practices - Updated",
Map.of(
"docId", "AIML-001",
"version", "2.0",
"lastUpdated", "2024-02-01"
)
);

// First, delete the old version using filter expression
Filter.Expression deleteOldVersion = new Filter.Expression(
Filter.ExpressionType.AND,
new Filter.Expression(
Filter.ExpressionType.EQ,
new Filter.Key("docId"),
new Filter.Value("AIML-001")
),
new Filter.Expression(
Filter.ExpressionType.EQ,
new Filter.Key("version"),
new Filter.Value("1.0")
)
);
vectorStore.delete(deleteOldVersion);

// Add the new version
vectorStore.add(List.of(documentV2));

// Verify only v2 exists
SearchRequest request = SearchRequest.builder()
.query("AI and Machine Learning")
.filterExpression("docId == 'AIML-001'")
.build();
List<Document> results = vectorStore.similaritySearch(request);
// results will contain only v2 of the document

您也可以使用字符串过滤表达式来实现相同的效果:

// Delete old version using string filter
vectorStore.delete("docId == 'AIML-001' AND version == '1.0'");

// Add new version
vectorStore.add(List.of(documentV2));

删除文档时的性能考虑​

  • 当你确切知道要删除哪些文档时,通过 ID 列表删除通常更快。

  • 基于过滤器的删除可能需要扫描索引以找到匹配的文档;然而,这取决于向量存储的具体实现。

  • 大规模删除操作应进行批量处理,以避免系统过载。

  • 在基于文档属性进行删除时,考虑使用过滤表达式,而不是先收集 ID。

理解向量​

本节概述​