OpenSearch
本节将指导您设置 OpenSearchVectorStore
以存储文档嵌入并执行相似性搜索。
This section walks you through setting up OpenSearchVectorStore
to store document embeddings and perform similarity searches.
OpenSearch 是一个开源的搜索和分析引擎,最初从 Elasticsearch 分叉而来,采用 Apache License 2.0 许可证分发。它通过简化 AI 生成资产的集成和管理来增强 AI 应用程序开发。OpenSearch 支持向量、词法和混合搜索功能,利用先进的向量数据库功能来促进低延迟查询和相似性搜索,详见 vector database page 。
OpenSearch is an open-source search and analytics engine originally forked from Elasticsearch, distributed under the Apache License 2.0. It enhances AI application development by simplifying the integration and management of AI-generated assets. OpenSearch supports vector, lexical, and hybrid search capabilities, leveraging advanced vector database functionalities to facilitate low-latency queries and similarity searches as detailed on the vector database page.
OpenSearch k-NN 功能允许用户查询大型数据集中的向量嵌入。嵌入是数据对象(如文本、图像、音频或文档)的数值表示。嵌入可以存储在索引中,并使用各种相似性函数进行查询。
The OpenSearch k-NN functionality allows users to query vector embeddings from large datasets. An embedding is a numerical representation of a data object, such as text, image, audio, or document. Embeddings can be stored in the index and queried using various similarity functions.
Prerequisites
-
一个正在运行的 OpenSearch 实例。以下选项可用:
-
A running OpenSearch instance. The following options are available:
-
如果需要,一个用于 EmbeddingModel 的 API 密钥,以生成由
OpenSearchVectorStore
存储的嵌入。 -
If required, an API key for the EmbeddingModel to generate the embeddings stored by the
OpenSearchVectorStore
.
Auto-configuration
Spring AI 自动配置、启动器模块的工件名称发生了重大变化。请参阅 upgrade notes 以获取更多信息。 There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the upgrade notes for more information. |
Spring AI 为 OpenSearch 向量存储提供了 Spring Boot 自动配置。要启用它,请将以下依赖项添加到您的项目 Maven pom.xml
文件中:
Spring AI provides Spring Boot auto-configuration for the OpenSearch Vector Store.
To enable it, add the following dependency to your project’s Maven pom.xml
file:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-vector-store-opensearch</artifactId>
</dependency>
或添加到您的 Gradle build.gradle
构建文件中:
or to your Gradle build.gradle
build file:
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-vector-store-opensearch'
}
|
Refer to the Dependency Management section to add the Spring AI BOM to your build file. |
对于 Amazon OpenSearch Service,请改用以下依赖项:
For Amazon OpenSearch Service, use these dependencies instead:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-vector-store-opensearch</artifactId>
</dependency>
或者对于 Gradle:
or for Gradle:
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-vector-store-opensearch'
}
请查看矢量存储的 configuration parameters 列表,了解默认值和配置选项。
Please have a look at the list of _configuration_properties for the vector store to learn about the default values and configuration options.
此外,您还需要一个配置好的 EmbeddingModel
bean。有关更多信息,请参阅 EmbeddingModel 部分。
Additionally, you will need a configured EmbeddingModel
bean. Refer to the EmbeddingModel section for more information.
现在您可以在应用程序中自动装配 OpenSearchVectorStore
作为向量存储:
Now you can auto-wire the OpenSearchVectorStore
as a vector store in your application:
@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());
Configuration Properties
要连接到 OpenSearch 并使用 OpenSearchVectorStore
,您需要提供实例的访问详细信息。可以通过 Spring Boot 的 application.yml
提供一个简单的配置:
To connect to OpenSearch and use the OpenSearchVectorStore
, you need to provide access details for your instance.
A simple configuration can be provided via Spring Boot’s 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
:
Properties starting with spring.ai.vectorstore.opensearch.*
are used to configure the OpenSearchVectorStore
:
Property | Description | Default Value |
---|---|---|
|
URIs of the OpenSearch cluster endpoints |
- |
|
Username for accessing the OpenSearch cluster |
- |
|
Password for the specified username |
- |
|
Name of the index to store vectors |
|
|
Whether to initialize the required schema |
|
|
The similarity function to use |
|
|
Time to wait for response from the opposite endpoint. 0 - infinity. |
- |
|
Time to wait until connection established. 0 - infinity. |
- |
|
Path prefix for OpenSearch API endpoints. Useful when OpenSearch is behind a reverse proxy with a non-root path. |
- |
|
Name of the SSL Bundle to use in case of SSL connection |
- |
|
Hostname of the OpenSearch instance |
- |
|
AWS service name |
- |
|
AWS access key |
- |
|
AWS secret key |
- |
|
AWS region |
- |
您可以使用 You can control whether the AWS-specific OpenSearch auto-configuration is enabled using the
此回退逻辑确保用户可以明确控制 OpenSearch 集成类型,防止在不需要时意外激活 AWS 特定逻辑。 This fallback logic ensures that users have explicit control over the type of OpenSearch integration, preventing accidental activation of AWS-specific logic when not desired. |
当 OpenSearch 运行在使用非根路径的反向代理后面时, The |
以下相似性函数可用:
The following similarity functions are available:
-
@s0 - 默认,适用于大多数用例。测量向量之间的余弦相似度。
-
cosinesimil
- Default, suitable for most use cases. Measures cosine similarity between vectors. -
@s1 - 向量之间的曼哈顿距离。
-
l1
- Manhattan distance between vectors. -
@s2 - 向量之间的欧几里得距离。
-
l2
- Euclidean distance between vectors. -
@s3 - 向量之间的切比雪夫距离。
-
linf
- Chebyshev distance between vectors.
Manual Configuration
除了使用 Spring Boot 自动配置,你还可以手动配置 OpenSearch 向量存储。为此,你需要将 @s4 添加到你的项目中:
Instead of using the Spring Boot auto-configuration, you can manually configure the OpenSearch vector store. For this you need to add the spring-ai-opensearch-store
to your project:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-opensearch-store</artifactId>
</dependency>
或添加到您的 Gradle build.gradle
构建文件中:
or to your Gradle build.gradle
build file:
dependencies {
implementation 'org.springframework.ai:spring-ai-opensearch-store'
}
|
Refer to the Dependency Management section to add the Spring AI BOM to your build file. |
创建 OpenSearch 客户端 bean:
Create an OpenSearch client bean:
@Bean
public OpenSearchClient openSearchClient() {
RestClient restClient = RestClient.builder(
HttpHost.create("http://localhost:9200"))
.build();
return new OpenSearchClient(new RestClientTransport(
restClient, new JacksonJsonpMapper()));
}
然后使用构建器模式创建 @s5 bean:
Then create the OpenSearchVectorStore
bean using the builder pattern:
@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")));
}
Metadata Filtering
你也可以在 OpenSearch 中利用通用的、可移植的 @s6。
You can leverage the generic, portable metadata filters with OpenSearch as well.
例如,你可以使用文本表达式语言:
For example, you can use either the text expression language:
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 以编程方式:
or programmatically using the 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 @s7。 |
Those (portable) filter expressions get automatically converted into the proprietary OpenSearch Query string query. |
例如,此可移植的筛选器表达式:
For example, this portable filter expression:
author in ['john', 'jill'] && 'article_type' == 'blog'
转换为专有的 OpenSearch 过滤器格式:
is converted into the proprietary OpenSearch filter format:
(metadata.author:john OR jill) AND metadata.article_type:blog
Accessing the Native Client
OpenSearch 向量存储实现通过 @s9 方法提供对底层原生 OpenSearch 客户端 (@s8) 的访问:
The OpenSearch Vector Store implementation provides access to the underlying native OpenSearch client (OpenSearchClient
) through the getNativeClient()
method:
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 特有的功能和操作,这些功能和操作可能不会通过 @s10 接口公开。
The native client gives you access to OpenSearch-specific features and operations that might not be exposed through the VectorStore
interface.