弹性搜索
本节将引导你如何设置Elasticsearch。VectorStore用于存储文档嵌入并进行相似性搜索。
Elasticsearch 是一个基于 Apache Lucene 库的开源搜索和分析引擎。
自动配置
|
春季AI自动配置、起始模块的工件名称发生了重大变化。 更多信息请参阅升级说明。 |
Spring AI 为 Elasticsearch 向量存储提供了 Spring Boot 自动配置。
要启用它,请在项目的 Maven 中添加以下依赖pom.xml或者Gradlebuild.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'
}
|
对于3.3.0之前的spring-boot版本,必须在8.13.3版本中明确添加elasticsearch-java>依赖,否则旧版本将与所执行的查询不兼容:
|
| 请参考依赖管理部分,将Spring AI的物料清单添加到你的构建文件中。 |
| 请参阅“遗物仓库”部分,将Maven Central和/或快照仓库添加到你的构建文件中。 |
向量存储实现可以帮你初始化所需的模式,但你必须通过指定初始化模式在适当的构造函数中进行布尔值,或通过设置…initialize-schema=true在application.properties文件。
或者,你也可以选择退出初始化,使用Elasticsearch客户端手动创建索引,这在索引需要高级映射或额外配置时非常有用。
| 这是一个颠覆性的变革!在早期版本的 Spring AI 中,这种模式初始化是默认的。 |
请查看矢量存储的配置参数列表,了解默认值和配置选项。
这些属性也可以通过配置ElasticsearchVectorStoreOptions豆。
此外,你还需要一个配置嵌入模型豆。 更多信息请参阅嵌入模型部分。
现在你可以自动接线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 Boot 属性春季.elasticsearch。*用于配置 Elasticsearch 客户端:
| 属性 | 描述 | 默认值 |
|---|---|---|
|
连接超时用于与 Elasticsearch 通信。 |
|
|
用于Elasticsearch认证的密码。 |
- |
|
用户名用于Elasticsearch认证。 |
- |
|
使用Elasticsearch实例的逗号分隔列表。 |
|
|
在发送给 Elasticsearch 的每个请求路径中添加前缀。 |
- |
|
在失败后安排的嗅探执行延迟。 |
|
|
连续普通嗅探执行之间的间隔。 |
|
|
SSL 捆绑包名称。 |
- |
|
是否启用客户端和Elasticsearch之间的套接字保持活力。 |
|
|
与 Elasticsearch 通信时使用的套接字超时。 |
|
性质以spring.ai.vectorstore.elasticsearch.*用于配置ElasticsearchVectorStore:
| 属性 | 描述 | 默认值 |
|---|---|---|
|
是否初始化所需的模式 |
|
|
用于存储向量的索引名称 |
|
|
向量中的维数 |
|
|
相似函数 |
|
|
搜索向量场的名称 |
|
以下相似度函数可用:
-
余弦- 默认,适用于大多数用例。测量向量之间的余弦相似度。 -
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());
或者程序化地使用滤波。表达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 查询字符串查询。 |
例如,这个可移植的Filter表达式:
author in ['john', 'jill'] && 'article_type' == 'blog'
转换为专有的ElasticsearchFilter格式:
(metadata.author:john OR jill) AND metadata.article_type:blog
手动配置
你可以手动配置Elasticsearch向量存储,而不是用Spring Boot的自动配置。为此你需要添加Spring-ai-elasticsearch-store致你的项目:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-elasticsearch-store</artifactId>
</dependency>
或者去你的Gradlebuild.gradle构建文件。
dependencies {
implementation 'org.springframework.ai:spring-ai-elasticsearch-store'
}
创建一个弹性搜索Rest客户端豆。
阅读 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
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 向量存储实现提供了对底层原生 Elasticsearch 客户端的访问(Elasticsearch客户端)通过getNativeClient()方法:
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接口。