|
此版本仍在开发中,尚未被视为稳定版。如需最新的快照版本,请使用 Spring AI 1.1.3! |
Elasticsearch
本节将引导您设置 Elasticsearch VectorStore 以存储文档嵌入并执行相似性搜索。
Elasticsearch 是基于 Apache Lucene 库的开源搜索和分析引擎。
Auto-configuration
|
Spring AI自动配置和starter模块的artifact名称有了重大变化。 请参阅升级说明获取更多信息。 |
Spring AI 为 Elasticsearch 向量存储提供 Spring Boot 自动配置。
要启用它,请将以下依赖项添加到项目中的 Maven pom.xml 或 Gradle build.gradle 构建文件中:
-
Maven
-
Gradle
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-vector-store-elasticsearch</artifactId>
</dependency>
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-vector-store-elasticsearch'
}
|
对于 spring-boot 版本低于 3.3.0,需要显式添加 elasticsearch-java 依赖,并指定版本大于 8.13.3,否则将使用的较旧版本与执行的查询不兼容:
|
| 请参阅依赖管理部分,将Spring AI BOM添加到您的构建文件中。 |
| 请参阅 构件仓库 部分,将 Maven 中央仓库和/或快照仓库添加到您的构建文件中。 |
向量存储实现可以为您初始化所需的模式,但您必须通过在适当的构造函数中指定initializeSchema或在application.properties文件中设置…initialize-schema=true来选择加入。
或者,您可以选择退出初始化,使用Elasticsearch客户端手动创建索引,如果索引需要高级映射或额外配置,这将很有用。
| 这是一个破坏性变更!在早期版本的 Spring AI 中,此架构初始化是默认发生的。 |
请查看向量存储的配置参数列表,了解默认值和配置选项。
这些属性也可以通过配置ElasticsearchVectorStoreOptions bean来设置。
此外,您还需要一个已配置的 EmbeddingModel bean。有关更多信息,请参阅 EmbeddingModel 部分。
现在你可以在你的应用程序中自动装配ElasticsearchVectorStore作为向量存储。
@Autowired VectorStore vectorStore;
// ...
List <Document> documents = List.of(
new Document("Spring AI rocks!! Spring AI rocks!! 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 Elasticsearch
vectorStore.add(documents);
// Retrieve documents similar to a query
List<Document> results = this.vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build());
配置属性
要连接到 Elasticsearch 并使用 ElasticsearchVectorStore,您需要提供实例的访问详细信息。
可以通过 Spring Boot 的 application.yml 提供一个简单的配置,
spring:
elasticsearch:
uris: <elasticsearch instance URIs>
username: <elasticsearch username>
password: <elasticsearch password>
ai:
vectorstore:
elasticsearch:
initialize-schema: true
index-name: custom-index
dimensions: 1536
similarity: cosine
以 spring.elasticsearch.* 开头的 Spring Boot 属性用于配置 Elasticsearch 客户端:
| <property> </property> | <description> </description> | 默认值 |
|---|---|---|
|
与 Elasticsearch 通信时使用的连接超时时间。 |
|
|
用于与 Elasticsearch 进行身份验证的密码。 |
- |
|
用于与 Elasticsearch 进行身份验证的用户名。 |
- |
|
要使用的 Elasticsearch 实例的逗号分隔列表。 |
|
|
添加到发送至 Elasticsearch 的每个请求路径前的前缀。 |
- |
|
在失败后安排执行的嗅探操作的延迟时间。 |
|
|
连续普通嗅探执行之间的间隔。 |
|
|
SSL 证书包名称。 |
- |
|
是否在客户端与 Elasticsearch 之间启用套接字保持连接(keep alive)。 |
|
|
与 Elasticsearch 通信时使用的套接字超时时间。 |
|
以 spring.ai.vectorstore.elasticsearch.* 开头的属性用于配置 ElasticsearchVectorStore:
| <property> </property> | <description> </description> | 默认值 |
|---|---|---|
|
是否初始化所需的模式 |
|
|
用于存储向量的索引名称 |
|
|
向量中的维度数量 |
|
|
要使用的相似度函数 |
|
|
要搜索的向量字段名称 |
|
以下相似性函数可用:
-
cosine- 默认值,适用于大多数使用场景。测量向量之间的余弦相似度。 -
l2_norm- 向量之间的欧式距离。较低的值表示更高的相似度。 -
dot_product- 对于归一化向量(例如,OpenAI 嵌入)具有最佳性能。
更多详细信息请参阅 Elasticsearch 文档 中关于密集向量的内容。
元数据过滤
您还可以在 Elasticsearch 中利用通用、可移植的 元数据过滤器。
例如,您可以使用文本表达式语言:
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());
| 这些(可移植的)过滤表达式将自动转换为专有的 Elasticsearch 查询字符串查询。 |
例如,此可移植的过滤器表达式:
author in ['john', 'jill'] && 'article_type' == 'blog'
被转换为专有的 Elasticsearch 过滤器格式:
(metadata.author:john OR jill) AND metadata.article_type:blog
手动配置
不使用 Spring Boot 自动配置,你可以手动配置 Elasticsearch 向量存储。为此,你需要将 spring-ai-elasticsearch-store 添加到你的项目中:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-elasticsearch-store</artifactId>
</dependency>
请将以下内容添加到您的Gradle build.gradle 构建文件中。
dependencies {
implementation 'org.springframework.ai:spring-ai-elasticsearch-store'
}
创建一个 Elasticsearch RestClient bean。
阅读 Elasticsearch 文档 以获取有关自定义 RestClient 配置的更详细信息。
@Bean
public RestClient restClient() {
return RestClient.builder(new HttpHost("<host>", 9200, "http"))
.setDefaultHeaders(new Header[]{
new BasicHeader("Authorization", "Basic <encoded username and password>")
})
.build();
}
然后使用构建器模式创建 ElasticsearchVectorStore bean:
@Bean
public VectorStore vectorStore(RestClient restClient, EmbeddingModel embeddingModel) {
ElasticsearchVectorStoreOptions options = new ElasticsearchVectorStoreOptions();
options.setIndexName("custom-index"); // Optional: defaults to "spring-ai-document-index"
options.setSimilarity(COSINE); // Optional: defaults to COSINE
options.setDimensions(1536); // Optional: defaults to model dimensions or 1536
return ElasticsearchVectorStore.builder(restClient, embeddingModel)
.options(options) // Optional: use custom options
.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")));
}
访问原生客户端
Elasticsearch 向量存储实现通过 getNativeClient() 方法提供对底层原生 Elasticsearch 客户端(ElasticsearchClient)的访问:
ElasticsearchVectorStore vectorStore = context.getBean(ElasticsearchVectorStore.class);
Optional<ElasticsearchClient> nativeClient = vectorStore.getNativeClient();
if (nativeClient.isPresent()) {
ElasticsearchClient client = nativeClient.get();
// Use the native client for Elasticsearch-specific operations
}
原生客户端提供了对 Elasticsearch 特定功能和操作的访问,这些功能和操作可能不会通过 VectorStore 接口暴露出来。