OpenSearch

本站(springdoc.cn)中的内容来源于 spring.io ,原始版权归属于 spring.io。由 springdoc.cn 进行翻译,整理。可供个人学习、研究,未经许可,不得进行任何转载、商用或与之相关的行为。 商标声明:Spring 是 Pivotal Software, Inc. 在美国以及其他国家的商标。

本节将指导你设置 OpenSearchVectorStore 用于存储文档嵌入并执行相似性搜索。

OpenSearch 是一个开源的搜索与分析引擎,最初是从 Elasticsearch 分叉而来,遵循 Apache 2.0 许可证发布。它通过简化 AI 生成内容的集成与管理,增强了 AI 应用程序的开发能力。OpenSearch 支持向量搜索、词法搜索以及混合搜索功能,借助先进的向量数据库功能,支持低延迟查询和相似性搜索,如 向量数据库页面 中所述。

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

先决条件

如有需要,可为 EmbeddingModel 提供一个 API 密钥,用于生成由 OpenSearchVectorStore 存储的嵌入向量。

自动配置

Spring AI 的自动配置和 Starter 模块的工件名称发生了重大变化。请参阅 升级说明 以获取更多信息。

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'
}
请参阅 “依赖管理” 部分,将 Spring AI BOM 添加到你的构建文件中。

对于 Amazon OpenSearch Service,请改用以下依赖:

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

对于 Gradle:

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

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

此外,你还需要配置一个 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")));

// 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:
  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.ai.vectorstore.opensearch.uris

OpenSearch 集群端点的 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

是否初始化所需的 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-prefix

OpenSearch API 端点的路径前缀。当 OpenSearch 位于带有非 ROOT 路径的反向代理后面时非常有用。

-

spring.ai.vectorstore.opensearch.ssl-bundle

在使用 SSL 连接时要使用的 SSL Bundle 名称

-

spring.ai.vectorstore.opensearch.aws.host

OpenSearch 实例的主机名

-

spring.ai.vectorstore.opensearch.aws.service-name

AWS 服务名称

-

spring.ai.vectorstore.opensearch.aws.access-key

AWS access key

-

spring.ai.vectorstore.opensearch.aws.secret-key

AWS secret key

-

spring.ai.vectorstore.opensearch.aws.region

AWS region

-

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

  • 如果将此属性设置为 false,即使类路径中存在 AWS SDK 类,也会激活非 AWS 的 OpenSearch 配置。这允许你在那些为了其他服务而引入了 AWS SDK 的环境中,使用自托管或第三方 OpenSearch 集群。

  • 如果 AWS SDK 类不存在,则始终使用非 AWS 配置。

  • 如果 AWS SDK 类存在,且该属性未设置或设置为 true,则默认使用 AWS 特定的配置。

这种回退逻辑确保用户能够显式控制所使用的 OpenSearch 集成类型,在不需要时防止意外激活 AWS 特定的逻辑。

path-prefix 属性允许你在 OpenSearch 运行于使用非 ROOT 路径的反向代理后面时,指定一个自定义的路径前缀。例如,如果你的 OpenSearch 实例是通过 example.com/opensearch/ 而不是 example.com/ `访问的,则应设置 `path-prefix: /opensearch

以下是可用的相似性函数:

  • cosinesimil - 默认,适用于大多数使用场景。用于衡量向量之间的余弦相似性。

  • l1 - 向量之间的曼哈顿距离。

  • l2 - 向量之间的欧几里得距离。

  • linf - 向量之间的切比雪夫距离。

手动配置

除了使用 Spring Boot 的自动配置外,你也可以手动配置 OpenSearch 向量存储。为此,你需要将 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 添加到你的构建文件中。

创建 OpenSearchClient Bean:

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

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

然后使用 Builder 模式创建 OpenSearchVectorStore Bean:

@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 的通用、可移植的 元数据过滤器

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

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();
    // Use the native client for OpenSearch-specific operations
}

原生客户端使你可以访问 VectorStore 接口可能未暴露的、OpenSearch 特有的功能和操作。