MongoDB Atlas
本节将引导您设置 MongoDB Atlas 作为向量存储,以便与 Spring AI 一起使用。
This section walks you through setting up MongoDB Atlas as a vector store to use with Spring AI.
What is MongoDB Atlas?
MongoDB Atlas 是 MongoDB 在 AWS、Azure 和 GCP 中提供的完全托管的云数据库。Atlas 支持在您的 MongoDB 文档数据上进行原生向量搜索和全文搜索。
MongoDB Atlas is the fully-managed cloud database from MongoDB available in AWS, Azure, and GCP. Atlas supports native Vector Search and full text search on your MongoDB document data.
MongoDB Atlas Vector Search 允许您将嵌入存储在 MongoDB 文档中,创建向量搜索索引,并使用近似最近邻算法 (Hierarchical Navigable Small Worlds) 执行 KNN 搜索。您可以在 MongoDB 聚合阶段使用 $vectorSearch
聚合运算符对向量嵌入执行搜索。
MongoDB Atlas Vector Search allows you to store your embeddings in MongoDB documents, create vector search indexes, and perform KNN searches with an approximate nearest neighbor algorithm (Hierarchical Navigable Small Worlds).
You can use the $vectorSearch
aggregation operator in a MongoDB aggregation stage to perform a search on your vector embeddings.
Prerequisites
-
运行 MongoDB 版本 6.0.11、7.0.2 或更高版本的 Atlas 集群。要开始使用 MongoDB Atlas,您可以按照 here 的说明进行操作。确保您的 IP 地址包含在您的 Atlas 项目的 access list 中。
-
An Atlas cluster running MongoDB version 6.0.11, 7.0.2, or later. To get started with MongoDB Atlas, you can follow the instructions here. Ensure that your IP address is included in your Atlas project’s access list.
-
已启用向量搜索的正在运行的 MongoDB Atlas 实例
-
A running MongoDB Atlas instance with Vector Search enabled
-
已配置向量搜索索引的集合
-
Collection with vector search index configured
-
具有 id (字符串)、content (字符串)、metadata (文档) 和 embedding (向量) 字段的集合模式
-
Collection schema with id (string), content (string), metadata (document), and embedding (vector) fields
-
索引和集合操作的正确访问权限
-
Proper access permissions for index and collection operations
Auto-configuration
Spring AI 自动配置、启动器模块的工件名称发生了重大变化。请参阅 upgrade notes 以获取更多信息。 There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the upgrade notes for more information. |
Spring AI 为 MongoDB Atlas 向量存储提供 Spring Boot 自动配置。要启用它,请将以下依赖项添加到您的项目的 Maven pom.xml
文件中:
Spring AI provides Spring Boot auto-configuration for the MongoDB Atlas Vector Store.
To enable it, add the following dependency to your project’s Maven pom.xml
file:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-vector-store-mongodb-atlas</artifactId>
</dependency>
或添加到您的 Gradle build.gradle
构建文件中:
or to your Gradle build.gradle
build file:
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-vector-store-mongodb-atlas'
}
|
Refer to the Dependency Management section to add the Spring AI BOM to your build file. |
将Maven Central和/或Snapshot存储库添加到您的构建文件中,请参阅 Artifact Repositories 部分。 |
Refer to the Artifact Repositories section to add Maven Central and/or Snapshot Repositories to your build file. |
向量存储实现可以为您初始化所需的架构,但您必须通过在 application.properties
文件中设置 spring.ai.vectorstore.mongodb.initialize-schema=true
来选择启用。或者,您可以选择不进行初始化,并使用 MongoDB Atlas UI、Atlas Administration API 或 Atlas CLI 手动创建索引,这在索引需要高级映射或附加配置时非常有用。
The vector store implementation can initialize the requisite schema for you, but you must opt-in by setting spring.ai.vectorstore.mongodb.initialize-schema=true
in the application.properties
file.
Alternatively you can opt-out the initialization and create the index manually using the MongoDB Atlas UI, Atlas Administration API, or Atlas CLI, which can be useful if the index needs advanced mapping or additional configuration.
这是一个重大更改!在早期版本的Spring AI中,此架构初始化是默认发生的。 |
this is a breaking change! In earlier versions of Spring AI, this schema initialization happened by default. |
请查看向量存储的 configuration parameters 列表,以了解默认值和配置选项。
Please have a look at the list of mongodbvector-properties for the vector store to learn about the default values and configuration options.
此外,您还需要一个配置好的 EmbeddingModel
bean。有关更多信息,请参阅 EmbeddingModel 部分。
Additionally, you will need a configured EmbeddingModel
bean. Refer to the EmbeddingModel section for more information.
现在,您可以将 MongoDBAtlasVectorStore
作为向量存储在您的应用程序中进行自动装配:
Now you can auto-wire the MongoDBAtlasVectorStore
as a vector store in your application:
@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());
Configuration Properties
要连接到 MongoDB Atlas 并使用 MongoDBAtlasVectorStore
,您需要提供实例的访问详细信息。可以通过 Spring Boot 的 application.yml
提供一个简单的配置:
To connect to MongoDB Atlas and use the MongoDBAtlasVectorStore
, you need to provide access details for your instance.
A simple configuration can be provided via Spring Boot’s 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
:
Properties starting with spring.ai.vectorstore.mongodb.*
are used to configure the MongoDBAtlasVectorStore
:
Property | Description | Default Value |
---|---|---|
|
Whether to initialize the required schema |
|
|
The name of the collection to store the vectors |
|
|
The name of the vector search index |
|
|
The path where vectors are stored |
|
|
Comma-separated list of metadata fields that can be used for filtering |
empty list |
Manual Configuration
除了使用 Spring Boot 自动配置,您还可以手动配置 MongoDB Atlas 向量存储。为此,您需要将 spring-ai-mongodb-atlas-store
添加到您的项目中:
Instead of using the Spring Boot auto-configuration, you can manually configure the MongoDB Atlas vector store. For this you need to add the spring-ai-mongodb-atlas-store
to your project:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-mongodb-atlas-store</artifactId>
</dependency>
或添加到您的 Gradle build.gradle
构建文件中:
or to your Gradle build.gradle
build file:
dependencies {
implementation 'org.springframework.ai:spring-ai-mongodb-atlas-store'
}
创建 MongoTemplate
bean:
Create a MongoTemplate
bean:
@Bean
public MongoTemplate mongoTemplate() {
return new MongoTemplate(MongoClients.create("<mongodb atlas connection string>"), "<database name>");
}
然后使用构建器模式创建 MongoDBAtlasVectorStore
bean:
Then create the MongoDBAtlasVectorStore
bean using the builder pattern:
@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")));
}
Metadata Filtering
您也可以将通用的、可移植的 metadata filters 与 MongoDB Atlas 结合使用。
You can leverage the generic, portable metadata filters with MongoDB Atlas as well.
例如,你可以使用文本表达式语言:
For example, you can use either the text expression language:
vectorStore.similaritySearch(SearchRequest.builder()
.query("The World")
.topK(5)
.similarityThreshold(0.7)
.filterExpression("author in ['john', 'jill'] && article_type == 'blog'").build());
或使用 Filter.Expression
DSL 以编程方式:
or programmatically using the 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 过滤器表达式。 |
Those (portable) filter expressions get automatically converted into the proprietary MongoDB Atlas filter expressions. |
例如,此可移植的筛选器表达式:
For example, this portable filter expression:
author in ['john', 'jill'] && article_type == 'blog'
转换为专有的 MongoDB Atlas 过滤器格式:
is converted into the proprietary MongoDB Atlas filter format:
{
"$and": [
{
"$or": [
{ "metadata.author": "john" },
{ "metadata.author": "jill" }
]
},
{
"metadata.article_type": "blog"
}
]
}
Tutorials and Code Examples
开始使用 Spring AI 和 MongoDB:
To get started with Spring AI and MongoDB:
-
有关使用 Spring AI 和 MongoDB 进行检索增强生成 (RAG) 的综合代码示例,请参阅此 detailed tutorial 。
-
For a comprehensive code example demonstrating Retrieval Augmented Generation (RAG) with Spring AI and MongoDB, refer to this detailed tutorial.
Accessing the Native Client
MongoDB Atlas 向量存储实现通过 getNativeClient()
方法提供对底层原生 MongoDB 客户端 ( MongoClient
) 的访问:
The MongoDB Atlas Vector Store implementation provides access to the underlying native MongoDB client (MongoClient
) through the getNativeClient()
method:
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 特有功能和操作。
The native client gives you access to MongoDB-specific features and operations that might not be exposed through the VectorStore
interface.