12.8 OpenSearch

35 阅读5分钟

OpenSearch

本节将指导您设置 OpenSearchVectorStore 来存储文档嵌入向量并执行相似性搜索。

OpenSearch 是一个开源的搜索和分析引擎,最初从 Elasticsearch 分叉出来,使用 Apache License 2.0 许可证分发。它通过简化和集成管理 AI 生成的资产来增强 AI 应用程序开发。OpenSearch 支持向量、词汇和混合搜索功能,利用高级向量数据库功能来促进低延迟查询和相似性搜索,详情请参阅向量数据库页面

OpenSearch k-NN 功能允许用户从大型数据集中查询向量嵌入向量。嵌入向量是数据对象(如文本、图像、音频或文档)的数值表示。嵌入向量可以存储在索引中并使用各种相似性函数进行查询。

先决条件

自动配置

注意

Spring AI 自动配置和启动器模块的构件名称发生了重大变化。 请参阅升级说明了解更多信息。

Spring AI 为 OpenSearch 向量存储提供 Spring Boot 自动配置。 要启用它,请将以下依赖项添加到您项目的 Maven pom.xml 文件中:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-vector-store-opensearch</artifactId>
</dependency>

或添加到您的 Gradle build.gradle 构建文件中:

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-vector-store-opensearch'
}

提示

对于自托管和 Amazon OpenSearch Service,使用相同的依赖项。 请参阅依赖管理部分,将 Spring AI BOM 添加到您的构建文件中。

请查看向量存储的配置参数列表以了解默认值和配置选项。

此外,您需要一个配置好的 EmbeddingModel bean。有关更多信息,请参阅 EmbeddingModel 部分。

现在您可以在应用程序中将 OpenSearchVectorStore 作为向量存储自动装配:

@Autowired VectorStore vectorStore;

// ...

List<Document> documents = List.of(
    new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", Map.of("meta1", "meta1")),
    new Document("The World is Big and Salvation Lurks Around the Corner"),
    new Document("You walk forward facing the past and you turn back toward the future.", Map.of("meta2", "meta2")));

// 将文档添加到 OpenSearch
vectorStore.add(documents);

// 检索与查询相似的文档
List<Document> results = vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build());

配置属性

要连接到 OpenSearch 并使用 OpenSearchVectorStore,您需要提供实例的访问详细信息。 可以通过 Spring Boot 的 application.yml 提供简单的配置:

spring:
  ai:
    vectorstore:
      opensearch:
        uris: <opensearch instance URIs>
        username: <opensearch username>
        password: <opensearch password>
        index-name: spring-ai-document-index
        initialize-schema: true
        similarity-function: cosinesimil
        read-timeout: <time to wait for response>
        connect-timeout: <time to wait until connection established>
        path-prefix: <custom path prefix>
        ssl-bundle: <name of SSL bundle>
        aws:  # 仅用于 Amazon OpenSearch Service
          host: <aws opensearch host>
          service-name: <aws service name>
          access-key: <aws access key>
          secret-key: <aws secret key>
          region: <aws region>

spring.ai.vectorstore.opensearch.* 开头的属性用于配置 OpenSearchVectorStore

属性描述默认值
spring.ai.vectorstore.opensearch.urisOpenSearch 集群端点的 URI-
spring.ai.vectorstore.opensearch.username访问 OpenSearch 集群的用户名-
spring.ai.vectorstore.opensearch.password指定用户名的密码-
spring.ai.vectorstore.opensearch.index-name存储向量的索引名称spring-ai-document-index
spring.ai.vectorstore.opensearch.initialize-schema是否初始化所需的架构false
spring.ai.vectorstore.opensearch.similarity-function要使用的相似性函数cosinesimil
spring.ai.vectorstore.opensearch.read-timeout等待来自对端点响应的时间。0 - 无穷大。-
spring.ai.vectorstore.opensearch.connect-timeout等待直到连接建立的时间。0 - 无穷大。-
spring.ai.vectorstore.opensearch.path-prefixOpenSearch API 端点的路径前缀。当 OpenSearch 位于具有非根路径的反向代理后面时很有用。-
spring.ai.vectorstore.opensearch.ssl-bundleSSL 连接时使用的 SSL Bundle 的名称-
spring.ai.vectorstore.opensearch.aws.hostOpenSearch 实例的主机名-
spring.ai.vectorstore.opensearch.aws.service-nameAWS 服务名称-
spring.ai.vectorstore.opensearch.aws.access-keyAWS 访问密钥-
spring.ai.vectorstore.opensearch.aws.secret-keyAWS 密钥-
spring.ai.vectorstore.opensearch.aws.regionAWS 区域-

注意

您可以使用 spring.ai.vectorstore.opensearch.aws.enabled 属性控制是否启用 AWS 特定的 OpenSearch 自动配置。

  • 如果此属性设置为 false,则激活非 AWS OpenSearch 配置,即使类路径上存在 AWS SDK 类。这允许您在环境中使用自托管或第三方 OpenSearch 集群,其中存在 AWS SDK 以用于其他服务。
  • 如果 AWS SDK 类不存在,则始终使用非 AWS 配置。
  • 如果 AWS SDK 类存在且属性未设置或设置为 true,则默认使用 AWS 特定配置。

此回退逻辑确保用户对 OpenSearch 集成的类型具有明确的控制,防止在不需要时意外激活 AWS 特定逻辑。

注意

path-prefix 属性允许您在 OpenSearch 运行在具有非根路径的反向代理后面时指定自定义路径前缀。例如,如果您的 OpenSearch 实例可在 example.com/opensearch/ 而不是 example.com/ 访问,则您需要设置 path-prefix: /opensearch

可用的相似性函数包括:

  • cosinesimil - 默认,适用于大多数用例。测量向量之间的余弦相似度。
  • l1 - 向量之间的曼哈顿距离。
  • l2 - 向量之间的欧几里得距离。
  • linf - 向量之间的切比雪夫距离。

手动配置

您也可以手动配置 OpenSearch 向量存储,而不使用 Spring Boot 自动配置。为此,您需要将 spring-ai-opensearch-store 添加到您的项目中:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-opensearch-store</artifactId>
</dependency>

或添加到您的 Gradle build.gradle 构建文件中:

dependencies {
    implementation 'org.springframework.ai:spring-ai-opensearch-store'
}

提示

请参阅依赖管理部分,将 Spring AI BOM 添加到您的构建文件中。

创建 OpenSearch 客户端 bean:

@Bean
public OpenSearchClient openSearchClient() {
    RestClient restClient = RestClient.builder(
        HttpHost.create("http://localhost:9200"))
        .build();

    return new OpenSearchClient(new RestClientTransport(
        restClient, new JacksonJsonpMapper()));
}

然后使用构建器模式创建 OpenSearchVectorStore bean:

@Bean
public VectorStore vectorStore(OpenSearchClient openSearchClient, EmbeddingModel embeddingModel) {
    return OpenSearchVectorStore.builder(openSearchClient, embeddingModel)
        .index("custom-index")                // 可选:默认为 "spring-ai-document-index"
        .similarityFunction("l2")             // 可选:默认为 "cosinesimil"
        .initializeSchema(true)               // 可选:默认为 false
        .batchingStrategy(new TokenCountBatchingStrategy()) // 可选:默认为 TokenCountBatchingStrategy
        .build();
}

// 这可以是任何 EmbeddingModel 实现
@Bean
public EmbeddingModel embeddingModel() {
    return new OpenAiEmbeddingModel(new OpenAiApi(System.getenv("OPENAI_API_KEY")));
}

元数据过滤

您也可以在 OpenSearch 上使用通用、可移植的元数据过滤器

例如,您可以使用文本表达式语言:

vectorStore.similaritySearch(
    SearchRequest.builder()
        .query("The World")
        .topK(TOP_K)
        .similarityThreshold(SIMILARITY_THRESHOLD)
        .filterExpression("author in ['john', 'jill'] && 'article_type' == 'blog'").build());

或使用 Filter.Expression DSL 以编程方式:

FilterExpressionBuilder b = new FilterExpressionBuilder();

vectorStore.similaritySearch(SearchRequest.builder()
    .query("The World")
    .topK(TOP_K)
    .similarityThreshold(SIMILARITY_THRESHOLD)
    .filterExpression(b.and(
        b.in("author", "john", "jill"),
        b.eq("article_type", "blog")).build()).build());

注意

这些(可移植的)过滤器表达式会自动转换为专有的 OpenSearch 查询字符串查询

例如,这个可移植的过滤器表达式:

author in ['john', 'jill'] && 'article_type' == 'blog'

被转换为专有的 OpenSearch 过滤器格式:

(metadata.author:john OR jill) AND metadata.article_type:blog

访问本机客户端

OpenSearch 向量存储实现通过 getNativeClient() 方法提供对底层本机 OpenSearch 客户端(OpenSearchClient)的访问:

OpenSearchVectorStore vectorStore = context.getBean(OpenSearchVectorStore.class);
Optional<OpenSearchClient> nativeClient = vectorStore.getNativeClient();

if (nativeClient.isPresent()) {
    OpenSearchClient client = nativeClient.get();
    // 使用本机客户端进行 OpenSearch 特定操作
}

本机客户端为您提供可能未通过 VectorStore 接口公开的 OpenSearch 特定功能和操作。