MongoDB Atlas
本节将引导您设置 MongoDB Atlas 作为向量存储,以便与 Spring AI 一起使用。
什么是 MongoDB Atlas?
MongoDB Atlas 是 MongoDB 提供的全托管云数据库,可在 AWS、Azure 和 GCP 上使用。Atlas 支持对您的 MongoDB 文档数据进行原生的向量搜索 (Vector Search) 和全文搜索 (full text search)。
MongoDB Atlas 向量搜索 (Vector Search) 允许您将嵌入 (embeddings) 存储在 MongoDB 文档中,创建向量搜索索引 (vector search indexes),并使用近似最近邻算法 (approximate nearest neighbor algorithm,层状可导航小世界,HNSW) 执行 KNN 搜索。您可以在 MongoDB 聚合阶段 (aggregation stage) 中使用 $vectorSearch
聚合运算符 (aggregation operator) 对您的向量嵌入进行搜索。
自动配置
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 添加到您的构建文件中。 |
请参阅仓库部分,以将 Maven Central 和/或 Snapshot 仓库添加到您的构建文件中。 |
向量存储实现可以为您初始化所需的模式,但您必须通过在 application.properties
文件中设置 spring.ai.vectorstore.mongodb.initialize-schema=true
来选择启用此功能。或者,您可以选择禁用初始化,并使用 MongoDB Atlas UI、Atlas Administration 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
属性 | 描述 | 默认值 |
---|---|---|
|
是否初始化所需模式 |
|
|
用于存储向量的集合名称 |
|
|
向量搜索索引的名称 |
|
|
存储向量的路径 |
|
|
可用于过滤的元数据字段列表(逗号分隔) |
空列表 |
手动配置
您可以在不使用 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 特定功能和操作。