MongoDB Atlas
本节将引导您设置 MongoDB Atlas 作为向量存储,以与 Spring AI 一起使用。
什么是 MongoDB Atlas?
MongoDB Atlas 是 MongoDB 在 AWS、Azure 和 GCP 上提供的完全托管的云数据库。Atlas 支持对您的 MongoDB 文档数据进行原生向量搜索和全文搜索。
MongoDB Atlas 向量搜索 允许您将嵌入存储在 MongoDB 文档中,创建向量搜索索引,并使用近似最近邻算法(分层可导航小世界)执行 KNN 搜索。您可以在 MongoDB 聚合阶段使用 $vectorSearch 聚合操作符对您的向量嵌入执行搜索。
自动配置
|
Spring AI 自动配置、启动模块的工件名称发生了重大变化。请参阅 升级说明 以获取更多信息。 |
Spring AI 为 MongoDB Atlas 向量存储提供了 Spring Boot 自动配置。要启用它,请将以下依赖项添加到您项目的 Maven pom.xml 文件中
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-vector-store-mongodb-atlas</artifactId>
</dependency>
或添加到您的 Gradle build.gradle 构建文件中
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-vector-store-mongodb-atlas'
}
| 请参阅 依赖项管理 部分,将 Spring AI BOM 添加到您的构建文件中。 |
| 请参阅构件仓库部分,以将 Maven Central 和/或 Snapshot 仓库添加到您的构建文件。 |
向量存储实现可以为您初始化所需的模式,但您必须通过在 application.properties 文件中设置 spring.ai.vectorstore.mongodb.initialize-schema=true 来选择启用。或者,您可以选择不进行初始化,并使用 MongoDB Atlas UI、Atlas 管理 API 或 Atlas CLI 手动创建索引,如果索引需要高级映射或附加配置,这会很有用。
| 这是一个重大更改!在早期版本的 Spring AI 中,此模式初始化是默认发生的。 |
请查看向量存储的配置参数列表,以了解默认值和配置选项。
此外,您还需要一个配置的 `EmbeddingModel` bean。有关更多信息,请参阅EmbeddingModel部分。
现在,您可以在应用程序中将 MongoDBAtlasVectorStore 自动装配为向量存储
@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 MongoDB Atlas
vectorStore.add(documents);
// Retrieve documents similar to a query
List<Document> results = vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build());
配置属性
要连接到 MongoDB Atlas 并使用 MongoDBAtlasVectorStore,您需要提供实例的访问详细信息。可以通过 Spring Boot 的 application.yml 提供一个简单的配置
spring:
data:
mongodb:
uri: <mongodb atlas connection string>
database: <database name>
ai:
vectorstore:
mongodb:
initialize-schema: true
collection-name: custom_vector_store
index-name: custom_vector_index
path-name: custom_embedding
metadata-fields-to-filter: author,year
以 spring.ai.vectorstore.mongodb.* 开头的属性用于配置 MongoDBAtlasVectorStore
| 财产 | 描述 | 默认值 |
|---|---|---|
|
是否初始化所需的模式 |
|
|
存储向量的集合名称 |
|
|
向量搜索索引的名称 |
|
|
向量存储的路径 |
|
|
逗号分隔的元数据字段列表,可用于过滤 |
空列表 |
手动配置
您可以通过手动配置 MongoDB Atlas 向量存储,而不是使用 Spring Boot 自动配置。为此,您需要将 spring-ai-mongodb-atlas-store 添加到您的项目中
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-mongodb-atlas-store</artifactId>
</dependency>
或添加到您的 Gradle build.gradle 构建文件中
dependencies {
implementation 'org.springframework.ai:spring-ai-mongodb-atlas-store'
}
创建一个 MongoTemplate Bean
@Bean
public MongoTemplate mongoTemplate() {
return new MongoTemplate(MongoClients.create("<mongodb atlas connection string>"), "<database name>");
}
然后使用构建器模式创建 MongoDBAtlasVectorStore Bean
@Bean
public VectorStore vectorStore(MongoTemplate mongoTemplate, EmbeddingModel embeddingModel) {
return MongoDBAtlasVectorStore.builder(mongoTemplate, embeddingModel)
.collectionName("custom_vector_store") // Optional: defaults to "vector_store"
.vectorIndexName("custom_vector_index") // Optional: defaults to "vector_index"
.pathName("custom_embedding") // Optional: defaults to "embedding"
.numCandidates(500) // Optional: defaults to 200
.metadataFieldsToFilter(List.of("author", "year")) // Optional: defaults to empty list
.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")));
}
元数据过滤
您也可以将通用的、可移植的元数据过滤器与 MongoDB Atlas 结合使用。
例如,您可以使用文本表达式语言
vectorStore.similaritySearch(SearchRequest.builder()
.query("The World")
.topK(5)
.similarityThreshold(0.7)
.filterExpression("author in ['john', 'jill'] && article_type == 'blog'").build());
或使用 `Filter.Expression` DSL 以编程方式
FilterExpressionBuilder b = new FilterExpressionBuilder();
vectorStore.similaritySearch(SearchRequest.builder()
.query("The World")
.topK(5)
.similarityThreshold(0.7)
.filterExpression(b.and(
b.in("author", "john", "jill"),
b.eq("article_type", "blog")).build()).build());
| 这些(可移植的)过滤表达式会自动转换为专有的 MongoDB Atlas 过滤表达式。 |
例如,此可移植的过滤表达式
author in ['john', 'jill'] && article_type == 'blog'
被转换为专有的 MongoDB Atlas 过滤器格式
{
"$and": [
{
"$or": [
{ "metadata.author": "john" },
{ "metadata.author": "jill" }
]
},
{
"metadata.article_type": "blog"
}
]
}
教程和代码示例
要开始使用 Spring AI 和 MongoDB
-
请参阅Spring AI 集成入门指南。
-
有关使用 Spring AI 和 MongoDB 演示检索增强生成(RAG)的综合代码示例,请参阅此详细教程。
访问原生客户端
MongoDB Atlas 向量存储实现通过 getNativeClient() 方法提供对底层原生 MongoDB 客户端 (MongoClient) 的访问
MongoDBAtlasVectorStore vectorStore = context.getBean(MongoDBAtlasVectorStore.class);
Optional<MongoClient> nativeClient = vectorStore.getNativeClient();
if (nativeClient.isPresent()) {
MongoClient client = nativeClient.get();
// Use the native client for MongoDB-specific operations
}
原生客户端允许您访问 VectorStore 接口可能未公开的 MongoDB 特定功能和操作。