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

OpenSearch

本节将引导您完成配置OpenSearchVectorStore以存储文档嵌入并执行相似性搜索的过程。spring-doc.cadn.net.cn

OpenSearch中文版是一个开源的搜索和数据分析引擎,最初是从Elasticsearch分出来开发的,遵循Apache 2.0开源许可。它通过简化人工智能生成资产的集成和管理,提升了AI应用的开发效率。OpenSearch支持向量、词典式以及混合搜索能力,利用先进的向量数据库功能,以如详细内容请参考向量数据库页面spring-doc.cadn.net.cn

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

前提条件

自动配置

There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the 升级说明以获取更多信息。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>

或者添加到你的 Gradle build.gradle 构建文件中:spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-vector-store-opensearch'
}
For both self-hosted and 亚马逊OpenSearch服务, use the same dependency. Refer to the 依赖管理 section to add the Spring AI BOM to your build file.

请查看以下向量存储的配置参数列表,了解默认值和配置选项。这些配置参数的类型为C0。spring-doc.cadn.net.cn

此外,您还需要配置一个EmbeddingModel的豆。有关详细信息,请参阅EmbeddingModel部分。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.* 开头的属性用于配置 OpenSearchVectorStorespring-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

访问OELK集群的用户名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-document-indexspring-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

要使用的相似度函数spring-doc.cadn.net.cn

cosinesimilspring-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连接时使用的虚拟机证书名称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-keyspring-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

亚马逊 Web 服务的安全密钥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

你可以通过 代码块0 属性来控制 AWS 特定的 OpenSearch 自动配置是否启用。spring-doc.cadn.net.cn

  • 如果此属性设置为false,则启用非AWS OpenSearch配置,即使类路径上存在AWS SDK类。这允许您在其他服务的AWS SDK存在的环境中使用自托管或第三方的OpenSearch集群。spring-doc.cadn.net.cn

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

  • If AWS SDK classes are present and the property is not set or set to true, the AWS-specific configuration is used by default.spring-doc.cadn.net.cn

默认回车逻辑确保了用户可以明确控制OpenSearch集成类型,避免错误地启用不必要的AWS特定逻辑。spring-doc.cadn.net.cn

The 0属性允许你在OpenSearch运行在使用非根路径的反向代理服务器时指定自定义路径前缀。 例如,如果你的OpenSearch实例可从example.com/opensearch/访问而不是example.com/,你需要设置path-prefix: /opensearchspring-doc.cadn.net.cn

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

手动配置

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

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

或者添加到你的 Gradle build.gradle 构建文件中:spring-doc.cadn.net.cn

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

创建一个OpenSearch客户端Bean: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 Bean: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"
        .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());

或通过编程方式使用 Filter.Expression 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());
那些(便携的)过滤表达式会自动转换为 proprietary OpenSearch 查询字符串查询

例如,这个可移植的过滤表达式: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 客户端的方法(OpenSearchClient):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
}

native客户端让你能够访问OpenSearch特有的功能和操作,这些功能可能无法通过VectorStore接口暴露出来。spring-doc.cadn.net.cn