MongoDB Atlas
本节将引导您完成将 MongoDB Atlas 设置为向量存储以与 Spring AI 配合使用的步骤。
什么是 MongoDB Atlas?
MongoDB Atlas 是由 MongoDB 提供的全托管云数据库,可在 AWS、Azure 和 GCP 平台上使用。Atlas 支持对 MongoDB 文档数据进行原生向量搜索和全文搜索。
MongoDB Atlas 向量搜索 允许您将嵌入存储在 MongoDB 文档中,创建向量搜索索引,并使用近似最近邻算法(分层可导航小世界)执行 KNN 搜索。 您可以在 MongoDB 聚合阶段使用 $vectorSearch 聚合操作符来对您的向量嵌入执行搜索。
先决条件
- 运行 MongoDB 版本
6.0.11
、7.0.2
或更高版本的 Atlas 集群。要开始使用MongoDB Atlas
,您可以按照 此处 的说明操作。确保您的 IP 地址已包含在 Atlas 项目的 访问列表 中。 - 一个已启用向量搜索功能的运行中的 MongoDB Atlas 实例
- 配置了向量搜索索引的集合
- 集合模式包含 id(字符串)、content(字符串)、元数据(文档)和 embedding(向量)字段
- 索引和集合操作的适当访问权限
自动配置
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'
}
向量存储实现能够为您初始化所需的模式,但您必须通过在 application.properties
文件中设置 spring.ai.vectorstore.mongodb.initialize-schema=true
来选择启用。或者,您可以选择退出初始化,并使用 MongoDB Atlas 用户界面、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
:
属性 (Property) | 描述 (Description) | 默认值 (Default Value) |
---|---|---|
spring.ai.vectorstore.mongodb.initialize-schema |
是否初始化所需的模式 (Schema) | false |
spring.ai.vectorstore.mongodb.collection-name |
用于存储向量的集合 (Collection) 名称 | vector_store |
spring.ai.vectorstore.mongodb.index-name |
向量搜索索引的名称 | vector_index |
spring.ai.vectorstore.mongodb.path-name |
存储向量的字段路径 | embedding |
spring.ai.vectorstore.mongodb.metadata-fields-to-filter |
可用于过滤的元数据字段的逗号分隔列表 | 空列表 |
手动配置
不使用 Spring Boot 的自动配置,你可以手动配置 MongoDB Atlas 向量存储。为此,你需要在项目中添加 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"
}
]
}
访问原生客户端
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
}
原生客户端为您提供了访问 MongoDB 特定功能和操作的途径,这些可能未通过 VectorStore 接口公开。
最后编辑:Jeebiz 更新时间:2025-09-10 21:18