如需最新的快照版本,请使用 Spring AI 1.1.3spring-doc.cadn.net.cn

向量数据库

向量数据库是一种专用类型的数据库,在人工智能应用中发挥着至关重要的作用。spring-doc.cadn.net.cn

在向量数据库中,查询方式与传统关系型数据库不同。 它们不执行精确匹配,而是执行相似性搜索。 当给定一个向量作为查询时,向量数据库会返回与查询向量“相似”的向量。 关于如何在高层面上计算这种相似性的更多细节,请参阅 向量相似性spring-doc.cadn.net.cn

向量数据库用于将您的数据与 AI 模型集成。 使用它们的第一步是将您的数据加载到向量数据库中。 然后,当用户查询需要发送给 AI 模型时,会首先检索一组相似的文档。 这些文档随后作为用户问题的上下文,并与用户的查询一起发送给 AI 模型。 这项技术被称为检索增强生成(RAG)spring-doc.cadn.net.cn

以下部分介绍了用于使用多种向量数据库实现的 Spring AI 接口以及一些高级示例用法。spring-doc.cadn.net.cn

最后一节旨在揭示向量数据库中相似性搜索的底层方法。spring-doc.cadn.net.cn

API概述

本部分作为 Spring AI 框架中VectorStore接口及其相关类的指南。spring-doc.cadn.net.cn

Spring AI 提供了一个抽象的 API,用于通过 VectorStore 接口与向量数据库进行交互。spring-doc.cadn.net.cn

这里是 VectorStore 接口定义:spring-doc.cadn.net.cn

public interface VectorStore extends DocumentWriter {

    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) { ... };

    List<Document> similaritySearch(String query);

    List<Document> similaritySearch(SearchRequest request);

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

以及相关的 SearchRequest 构建器:spring-doc.cadn.net.cn

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 文档)的内容,并包含以字符串形式表示的文本。 它还包含以键值对形式存在的元数据,包括文件名等详细信息。spring-doc.cadn.net.cn

在插入向量数据库时,文本内容会通过嵌入模型转换为数值数组,即float[],称为向量嵌入。诸如Word2VecGLoVEBERT等嵌入模型,或 OpenAI 的text-embedding-ada-002,均可用于将单词、句子或段落转换为这些向量嵌入。spring-doc.cadn.net.cn

向量数据库的作用是存储这些嵌入并促进相似度搜索。它本身不生成嵌入。对于创建向量嵌入,应使用EmbeddingModelspring-doc.cadn.net.cn

接口中的 similaritySearch 个方法允许检索与给定查询字符串相似的文档。可以通过使用以下参数对这些方法进行微调:spring-doc.cadn.net.cn

  • k:一个整数,用于指定要返回的相似文档的最大数量。这通常被称为“前 Kspring-doc.cadn.net.cn

  • threshold:一个介于 0 到 1 之间的双精度浮点值,越接近 1 表示相似度越高。默认情况下,如果您将阈值设置为 0.75,则仅返回相似度高于该值的文档。spring-doc.cadn.net.cn

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

  • filterExpression:一个基于 ANTLR4 的外部领域特定语言(DSL),可接受字符串形式的过滤表达式。例如,对于名为 country、year 和 isActive 的元数据键,您可以使用如下表达式:country == 'UK' && year >= 2020 && isActive == true.spring-doc.cadn.net.cn

元数据过滤器 部分查找有关 Filter.Expression 的更多信息。spring-doc.cadn.net.cn

模式初始化

某些向量存储要求在使用前初始化其后端模式。 默认情况下,系统不会为您自动初始化。 您必须主动启用该功能,方法是为相应的构造函数参数传递 boolean,或者(如果使用 Spring Boot)在 application.propertiesapplication.yml 中将相应的 initialize-schema 属性设置为 true。 请查阅您所使用的向量存储的文档,以获取具体的属性名称。spring-doc.cadn.net.cn

批处理策略

在使用向量存储时,通常需要嵌入大量文档。 虽然看似可以一次性调用以嵌入所有文档,但这种方法可能会导致问题。 嵌入模型将文本作为Tokens(tokens)进行处理,并具有最大Tokens限制,通常称为上下文窗口大小。 此限制限制了单个嵌入请求中可以处理的文本量。 尝试在一次调用中嵌入过多Tokens可能会导致错误或嵌入被截断。spring-doc.cadn.net.cn

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

Spring AI 通过BatchingStrategy接口提供此功能,该接口允许根据文档的Tokens数量将其分批处理。spring-doc.cadn.net.cn

核心 BatchingStrategy 接口定义如下:spring-doc.cadn.net.cn

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

此接口定义了一个单一方法 batch,该方法接收一个文档列表并返回一个文档批次列表。spring-doc.cadn.net.cn

默认实现

Spring AI 提供了一个名为 TokenCountBatchingStrategy 的默认实现。 此策略根据文档的Tokens数量对文档进行批处理,确保每个批次不超过计算出的最大输入Tokens数。spring-doc.cadn.net.cn

TokenCountBatchingStrategy 的主要特性:spring-doc.cadn.net.cn

  1. 使用 OpenAI 的最大输入Tokens数(8191)作为默认上限。spring-doc.cadn.net.cn

  2. 包含一个保留百分比(默认为 10%),以提供应对潜在开销的缓冲。spring-doc.cadn.net.cn

  3. 计算实际的最大输入Tokens数为:actualMaxInputTokenCount = originalMaxInputTokenCount * (1 - RESERVE_PERCENTAGE)spring-doc.cadn.net.cn

该策略估算每个文档的Tokens数量,将它们分组为批次而不超过最大输入Tokens计数,如果单个文档超过此限制则抛出异常。spring-doc.cadn.net.cn

您还可以自定义TokenCountBatchingStrategy,以更好地满足您的特定需求。这可以通过在 Spring Boot @Configuration 类中创建带有自定义参数的新实例来实现。spring-doc.cadn.net.cn

以下是如何创建自定义 TokenCountBatchingStrategy Bean 的示例:spring-doc.cadn.net.cn

@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
        );
    }
}

在此配置中:spring-doc.cadn.net.cn

  1. EncodingType.CL100K_BASE: 指定用于分词的编码类型。此编码类型由 JTokkitTokenCountEstimator 使用,以准确估算Tokens数量。spring-doc.cadn.net.cn

  2. 8000: 设置最大输入Tokens数。该值应小于或等于嵌入模型的最大上下文窗口大小。spring-doc.cadn.net.cn

  3. 0.1: 设置保留百分比。该百分比表示从最大输入Tokens数中预留的Tokens比例。这为处理过程中可能出现的Tokens数量增加创建了缓冲空间。spring-doc.cadn.net.cn

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

一旦定义,这个自定义的 TokenCountBatchingStrategy Bean 将被应用程序中的 EmbeddingModel 实现自动使用,从而替换默认策略。spring-doc.cadn.net.cn

TokenCountBatchingStrategy 内部使用 TokenCountEstimator(具体为 JTokkitTokenCountEstimator)来计算Tokens数量,以实现高效批处理。这确保了基于指定编码类型的Tokens估算准确无误。spring-doc.cadn.net.cn

此外,TokenCountBatchingStrategy 通过允许您传入自己的 TokenCountEstimator 接口实现提供了灵活性。此功能使您能够使用针对特定需求定制的自定义Tokens计数策略。例如:spring-doc.cadn.net.cn

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 功能。启用该功能时,模型会静默截断超出最大长度的文本输入并继续处理;禁用该功能时,对于过长的输入则会抛出明确错误。spring-doc.cadn.net.cn

在使用自动截断与批处理策略时,您必须将批处理策略配置的输入Tokens数远高于模型的实际最大值。这可防止批处理策略在处理大型文档时抛出异常,从而让嵌入模型在内部处理截断操作。spring-doc.cadn.net.cn

自动截断的配置

启用自动截断时,请将批处理策略的最大输入Tokens数设置为远高于模型的实际限制。这可防止批处理策略针对大型文档抛出异常,从而让嵌入模型在内部处理截断。spring-doc.cadn.net.cn

以下是使用 Vertex AI 进行自动截断并自定义 BatchingStrategy,然后在 PgVectorStore 中使用它们的配置示例:spring-doc.cadn.net.cn

@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();
    }
}

在此配置中:spring-doc.cadn.net.cn

  1. 嵌入模型已启用自动截断功能,能够优雅地处理过大的输入。spring-doc.cadn.net.cn

  2. 批处理策略使用了一个人为设定的高Tokens限制(132,900),该值远大于模型的实际限制(20,000)。spring-doc.cadn.net.cn

  3. 向量存储使用配置的嵌入模型和自定义的 BatchingStrategy Bean。spring-doc.cadn.net.cn

为什么这样可行

这种方法之所以有效,是因为:spring-doc.cadn.net.cn

  1. TokenCountBatchingStrategy 会检查是否有任何单个文档超过配置的最大值,如果是,则抛出 IllegalArgumentExceptionspring-doc.cadn.net.cn

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

  3. 超过模型限制的文档或批次将被静默截断,并由嵌入模型的自动截断功能进行处理。spring-doc.cadn.net.cn

最佳实践

使用自动截断时:spring-doc.cadn.net.cn

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

  • 监控您的日志,查找来自嵌入模型的截断警告(注意:并非所有模型都会记录截断事件)。spring-doc.cadn.net.cn

  • 请考虑静默截断对您的嵌入质量的影响。spring-doc.cadn.net.cn

  • 使用示例文档进行测试,以确保截断后的嵌入仍符合您的要求。spring-doc.cadn.net.cn

  • 为未来的维护者记录此配置,因为它不符合标准。spring-doc.cadn.net.cn

虽然自动截断可以防止错误,但可能导致嵌入不完整。长文档末尾的重要信息可能会丢失。如果您的应用程序需要嵌入所有内容,请在嵌入之前将文档分割成较小的块。

Spring Boot 自动配置

如果您正在使用 Spring Boot 自动配置,则必须提供一个自定义的 BatchingStrategy Bean,以覆盖 Spring AI 自带的默认 Bean:spring-doc.cadn.net.cn

@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 时,将自动替换所有向量存储使用的默认批处理策略。spring-doc.cadn.net.cn

自定义实现

虽然 TokenCountBatchingStrategy 提供了稳健的默认实现,但您可以自定义批处理策略以满足您的特定需求。 这可以通过 Spring Boot 的自动配置来完成。spring-doc.cadn.net.cn

要自定义批处理策略,请在您的 Spring Boot 应用程序中定义一个 BatchingStrategy Bean:spring-doc.cadn.net.cn

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

此自定义 BatchingStrategy 随后将被您的应用程序中的 EmbeddingModel 实现自动使用。spring-doc.cadn.net.cn

Spring AI 支持的向量存储配置为使用默认值 TokenCountBatchingStrategy。 SAP Hana 向量存储当前未配置批处理功能。

VectorStore 实现

以下是 VectorStore 接口的可用实现:spring-doc.cadn.net.cn

未来的版本可能会支持更多实现。spring-doc.cadn.net.cn

如果您有一个需要 Spring AI 支持的向量数据库,请在 GitHub 上提交一个问题,或者更好的是,提交一个包含实现方案的拉取请求。spring-doc.cadn.net.cn

关于每个 VectorStore 实现的信息可以在本章的子章节中找到。spring-doc.cadn.net.cn

示例用法

要为向量数据库计算嵌入,您需要选择一个与所用高层 AI 模型相匹配的嵌入模型。spring-doc.cadn.net.cn

例如,使用 OpenAI 的 ChatGPT 时,我们使用 OpenAiEmbeddingModel 和一个名为 text-embedding-ada-002 的模型。spring-doc.cadn.net.cn

Spring Boot Starters的 OpenAI 自动配置会在 Spring 应用上下文中提供一个 EmbeddingModel 的实现,以便进行依赖注入。spring-doc.cadn.net.cn

将数据加载到向量存储的一般用法是您会在类似批处理的作业中执行的操作,首先将数据加载到 Spring AI 的 Document 类中,然后调用 save 方法。spring-doc.cadn.net.cn

给定一个指向表示 JSON 文件的源文件的 String 引用,我们使用 Spring AI 的 JsonReader 来加载 JSON 中的特定字段,将其拆分为小块,然后将这些小块传递给向量存储实现。 VectorStore 实现会计算嵌入向量,并将 JSON 及其嵌入向量存储到向量数据库中:spring-doc.cadn.net.cn

  @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模型时,会进行相似度搜索以检索相似文档,然后将这些文档“填充”到提示中作为用户问题的上下文。spring-doc.cadn.net.cn

   String question = <question from user>
   List<Document> similarDocuments = store.similaritySearch(this.question);

可以将其他选项传递给 similaritySearch 方法,以定义要检索的文档数量以及相似度搜索的阈值。spring-doc.cadn.net.cn

元数据过滤器

本节描述了可用于查询结果的各种过滤器。spring-doc.cadn.net.cn

过滤字符串

您可以将类似 SQL 的过滤器表达式作为 String 传递给其中一个 similaritySearch 重载方法。spring-doc.cadn.net.cn

请考虑以下示例:spring-doc.cadn.net.cn

Filter.Expression

您可以使用暴露流畅式 API 的 FilterExpressionBuilder 创建 Filter.Expression 的实例。 一个简单的示例如下:spring-doc.cadn.net.cn

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

您可以使用以下运算符构建复杂的表达式:spring-doc.cadn.net.cn

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

您可以使用以下运算符组合表达式:spring-doc.cadn.net.cn

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

考虑以下示例:spring-doc.cadn.net.cn

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

您还可以使用以下运算符:spring-doc.cadn.net.cn

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

考虑以下示例:spring-doc.cadn.net.cn

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

从向量存储中删除文档

Vector Store 接口提供了多种删除文档的方法,允许您通过特定的文档 ID 或使用过滤表达式来移除数据。spring-doc.cadn.net.cn

按文档 ID 删除

删除文档的最简单方式是提供文档 ID 列表:spring-doc.cadn.net.cn

void delete(List<String> idList);

此方法会移除所有 ID 与所提供列表中匹配的文档。 如果列表中的任何 ID 在存储中不存在,将被忽略。spring-doc.cadn.net.cn

示例用法
// 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()));

按过滤表达式删除

对于更复杂的删除条件,您可以使用过滤表达式:spring-doc.cadn.net.cn

void delete(Filter.Expression filterExpression);

此方法接受一个 Filter.Expression 对象,该对象定义了应删除哪些文档的条件。 当您需要根据文档的元数据属性进行删除时,它特别有用。spring-doc.cadn.net.cn

示例用法
// 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

通过字符串过滤表达式删除

为了方便,您还可以使用基于字符串的过滤表达式来删除文档:spring-doc.cadn.net.cn

void delete(String filterExpression);

此方法在内部将提供的字符串过滤器转换为 Filter.Expression 对象。 当您拥有字符串格式的过滤条件时,它非常有用。spring-doc.cadn.net.cn

示例用法
// 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 时的错误处理

所有删除方法在出错时可能会抛出异常:spring-doc.cadn.net.cn

最佳实践是将删除操作包裹在 try-catch 块中:spring-doc.cadn.net.cn

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

文档版本控制用例

一个常见的场景是管理文档版本,您需要上传文档的新版本并移除旧版本。以下是如何使用筛选表达式来处理此情况:spring-doc.cadn.net.cn

示例用法
// 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,
    Arrays.asList(
        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

您也可以使用字符串过滤表达式来实现相同的功能:spring-doc.cadn.net.cn

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

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

删除文档时的性能考虑

  • 当确切知道要删除哪些文档时,按 ID 列表删除通常更快。spring-doc.cadn.net.cn

  • 基于过滤器的删除可能需要扫描索引以查找匹配的文档;不过,这取决于向量存储的具体实现。spring-doc.cadn.net.cn

  • 大型删除操作应分批进行,以避免压垮系统。spring-doc.cadn.net.cn

  • 在基于文档属性进行删除时,请考虑使用过滤表达式,而不是先收集 ID。spring-doc.cadn.net.cn