OpenSearch

本节将引导你如何设置OpenSearchVectorStore用于存储文档嵌入并进行相似性搜索。spring-doc.cadn.net.cn

OpenSearch 是一个开源的搜索和分析引擎,最初从 Elasticsearch 分支而来,采用 Apache 许可证 2.0 发布。它通过简化AI生成资产的集成和管理,提升了AI应用的开发。OpenSearch 支持矢量、词汇和混合搜索功能,利用先进的矢量数据库功能,实现低延迟查询和相似度搜索,详见矢量数据库页面spring-doc.cadn.net.cn

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

前提条件

自动配置

春季AI自动配置、起始模块的工件名称发生了重大变化。 更多信息请参阅升级说明spring-doc.cadn.net.cn

Spring AI 为 OpenSearch 向量商店提供 Spring Boot 自动配置。 要启用它,请在项目的 Maven 中添加以下依赖pom.xml文件:spring-doc.cadn.net.cn

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

或者去你的Gradlebuild.gradle构建文件:spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-vector-store-opensearch'
}
无论是自主机还是亚马逊OpenSearch Service,都使用相同的依赖。 请参考依赖管理部分,将Spring AI的物料清单添加到你的构建文件中。

请查看矢量存储的配置参数列表,了解默认值和配置选项。spring-doc.cadn.net.cn

此外,你还需要一个配置嵌入模型豆。 更多信息请参阅嵌入模型部分。spring-doc.cadn.net.cn

现在你可以自动接线OpenSearchVectorStore作为你应用中的向量存储器:spring-doc.cadn.net.cn

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

// Add the documents to OpenSearch
vectorStore.add(documents);

// Retrieve documents similar to a query
List<Document> results = vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build());

配置属性

连接OpenSearch并使用OpenSearchVectorStore你需要为你的实例提供访问权限。 可以通过 Spring Boot 提供一个简单的配置application.yml:spring-doc.cadn.net.cn

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:  # Only for 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-doc.cadn.net.cn

属性 描述 默认值

spring.ai.vectorstore.opensearch.urisspring-doc.cadn.net.cn

OpenSearch 集群端点的 URIspring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vectorstore.opensearch.usernamespring-doc.cadn.net.cn

访问OpenSearch集群的用户名spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vectorstore.opensearch.passwordspring-doc.cadn.net.cn

指定用户名的密码spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vectorstore.opensearch.index-namespring-doc.cadn.net.cn

用于存储向量的索引名称spring-doc.cadn.net.cn

Spring-ai-文档索引spring-doc.cadn.net.cn

spring.ai.vectorstore.opensearch.initialize-schemaspring-doc.cadn.net.cn

是否初始化所需的模式spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.vectorstore.opensearch.similarity-functionspring-doc.cadn.net.cn

相似函数使用的是(cosinesimil, l1, l2, linf, innerproduct)spring-doc.cadn.net.cn

科西尼西米尔spring-doc.cadn.net.cn

spring.ai.vectorstore.opensearch.use-approximate-knnspring-doc.cadn.net.cn

是否使用近似k-NN以加快搜索速度。如果属实,则使用基于HNSW的近似搜索。如果错误,则使用精确的暴力破解k-NN。参见近似k-NN精确k-NNspring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.vectorstore.opensearch.dimensionsspring-doc.cadn.net.cn

向量嵌入的维数。用于创建近似k-NN的索引映射。如果未设置,则使用嵌入模型的维度。spring-doc.cadn.net.cn

1536spring-doc.cadn.net.cn

spring.ai.vectorstore.opensearch.mapping-jsonspring-doc.cadn.net.cn

为索引定制JSON映射。覆盖默认的映射生成。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vectorstore.opensearch.read-timeoutspring-doc.cadn.net.cn

等待对方端点的回复。0 - 无限。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vectorstore.opensearch.connect-timeoutspring-doc.cadn.net.cn

是时候等连接建立起来了。0 - 无限。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vectorstore.opensearch.path-prefixspring-doc.cadn.net.cn

OpenSearch API 端点的路径前缀。当OpenSearch位于带有非根路径的反向代理后面时,这非常有用。spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vectorstore.opensearch.ssl-bundlespring-doc.cadn.net.cn

SSL连接时使用的SSL捆绑包名称spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vectorstore.opensearch.aws.hostspring-doc.cadn.net.cn

OpenSearch 实例的主机名spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vectorstore.opensearch.aws.service-namespring-doc.cadn.net.cn

AWS 服务名称spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vectorstore.opensearch.aws.access-key。spring-doc.cadn.net.cn

AWS 访问密钥spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vectorstore.opensearch.aws.secret-keyspring-doc.cadn.net.cn

AWS 秘密密钥spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

spring.ai.vectorstore.opensearch.aws.regionspring-doc.cadn.net.cn

AWS 区域spring-doc.cadn.net.cn

-spring-doc.cadn.net.cn

你可以通过以下方式控制AWS专属的OpenSearch自动配置是否被启用spring.ai.vectorstore.opensearch.aws.enabled财产。spring-doc.cadn.net.cn

  • 如果该性质被设置为false,即使类路径上存在AWS SDK类,非AWS的OpenSearch配置也会被激活。这允许你在有 AWS SDK 用于其他服务的环境中使用自管理或第三方 OpenSearch 集群。spring-doc.cadn.net.cn

  • 如果没有 AWS SDK 类,则始终使用非 AWS 配置。spring-doc.cadn.net.cn

  • 如果存在AWS SDK类且该属性未被设置为true,默认使用AWS专用配置。spring-doc.cadn.net.cn

这种备用逻辑确保用户对OpenSearch集成类型拥有明确控制权,防止AWS专用逻辑在不被允许时意外激活。spring-doc.cadn.net.cn

路径前缀属性允许你在OpenSearch运行时指定自定义路径前缀,当OpenSearch运行在使用非根路径的反向代理时。 例如,如果你的OpenSearch实例可以访问于example.com/opensearch/而不是example.com/,你会设置路径前缀:/opensearch.spring-doc.cadn.net.cn

以下相似度函数可用:spring-doc.cadn.net.cn

手动配置

你可以手动配置OpenSearch向量存储,而不是使用Spring Boot的自动配置。为此你需要添加Spring-ai-opensearch-store致你的项目:spring-doc.cadn.net.cn

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

或者去你的Gradlebuild.gradle构建文件:spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-opensearch-store'
}
请参考依赖管理部分,将Spring AI的物料清单添加到你的构建文件中。

创建OpenSearch客户端豆:spring-doc.cadn.net.cn

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

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

然后创建OpenSearchVectorStore使用构建图纸的豆子:spring-doc.cadn.net.cn

@Bean
public VectorStore vectorStore(OpenSearchClient openSearchClient, EmbeddingModel embeddingModel) {
    return OpenSearchVectorStore.builder(openSearchClient, embeddingModel)
        .index("custom-index")                // Optional: defaults to "spring-ai-document-index"
        .similarityFunction("l2")             // Optional: defaults to "cosinesimil"
        .useApproximateKnn(true)              // Optional: defaults to false (exact k-NN)
        .dimensions(1536)                     // Optional: defaults to 1536 or embedding model's dimensions
        .initializeSchema(true)               // Optional: defaults to false
        .batchingStrategy(new TokenCountBatchingStrategy()) // Optional: defaults to TokenCountBatchingStrategy
        .build();
}

// This can be any EmbeddingModel implementation
@Bean
public EmbeddingModel embeddingModel() {
    return new OpenAiEmbeddingModel(new OpenAiApi(System.getenv("OPENAI_API_KEY")));
}

元数据过滤

你也可以利用OpenSearch的通用、可移植元数据过滤器spring-doc.cadn.net.cn

例如,你可以使用以下文本表达式语言:spring-doc.cadn.net.cn

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

或者程序化地使用滤波。表达DSL:spring-doc.cadn.net.cn

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查询字符串查询

例如,这个可移植的Filter表达式:spring-doc.cadn.net.cn

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

转换为专有的OpenSearch过滤器格式:spring-doc.cadn.net.cn

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

访问本地客户端

OpenSearch 向量存储实现提供了对底层原生 OpenSearch 客户端的访问(OpenSearch客户端)通过getNativeClient()方法:spring-doc.cadn.net.cn

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

if (nativeClient.isPresent()) {
    OpenSearchClient client = nativeClient.get();
    // Use the native client for OpenSearch-specific operations
}

原生客户端为您提供了OpenSearch专属的功能和作,这些可能无法通过VectorStore接口。spring-doc.cadn.net.cn