MongoDB Atlas
本节将引导你设置 MongoDB Atlas 作为向量存储,以与 Spring AI 配合使用。
什么是 MongoDB Atlas?
MongoDB Atlas 是 MongoDB 在 AWS、Azure 和 GCP 上提供的全托管云数据库。 Atlas 支持对 MongoDB 文档数据进行原生向量搜索和全文搜索。
MongoDB Atlas 向量搜索 允许你将嵌入存储在 MongoDB 文档中,创建向量搜索索引,并使用近似最近邻算法(分层可导航小世界)执行 KNN 搜索。
你可以在 MongoDB 聚合阶段使用 $vectorSearch
聚合操作符对向量嵌入执行搜索。
自动配置
Spring AI 自动配置、启动器模块的 artifact 名称发生了重大变化。 有关更多信息,请参阅 升级说明。 |
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 添加到你的构建文件中。 |
请参阅 Artifact 仓库 部分,将 Maven Central 和/或 Snapshot 仓库添加到你的构建文件中。 |
向量存储实现可以为你初始化所需的 schema,但你必须通过在 application.properties
文件中设置 spring.ai.vectorstore.mongodb.initialize-schema=true
来选择启用。
或者,你可以选择不进行初始化,并使用 MongoDB Atlas UI、Atlas Administration API 或 Atlas CLI 手动创建索引,如果索引需要高级映射或额外配置,这将非常有用。
这是一个重大变更!在早期版本的 Spring AI 中,此 schema 初始化是默认发生的。 |
请查看向量存储的 mongodbvector-properties 列表,以了解默认值和配置选项。
此外,你还需要一个配置好的 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
:
属性 | 描述 | 默认值 |
---|---|---|
|
是否初始化所需的 schema |
|
|
存储向量的集合名称 |
|
|
向量搜索索引的名称 |
|
|
存储向量的路径 |
|
|
可用于过滤的元数据字段的逗号分隔列表 |
空列表 |
手动配置
除了使用 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"
}
]
}
教程和代码示例
要开始使用 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 特有功能和操作。