MongoDB AtlasSphere
本节将指导你如何设置MongoDB Atlas作为向量数据库,与Spring AI集成。
MongoDB Atlas 是什么?
MongoDB Atlas 是 MongoDB 提供的全托管云数据库,支持在 AWS、Azure 和 GCP 平台上使用。 Atlas 支持对 MongoDB 文档数据进行本地向量搜索和全文搜索。
MongoDB Atlas Vector Search允许你在MongoDB文档中存储你的嵌入,创建向量搜索索引,并使用近似最近邻算法(Hierarchical Navigable Small Worlds)进行K近邻搜索。
你可以在MongoDB聚合阶段使用`$vectorSearch`聚合操作符对你的向量嵌入进行搜索。
前提条件
-
一个运行MongoDB版本6.0.11、7.0.2或更高版本的Atlas集群。要开始使用MongoDB Atlas,您可以按照< a t="C0">这里的指示进行。确保您的IP地址包含在您 Atlas项目的< a t="C1">访问列表中。
-
运行中的MongoDB Atlas实例,已启用向量搜索功能。
-
配置好的向量搜索索引集合
-
集合schema包含id字段(字符串)、内容字段(字符串)、元数据文档和嵌入(向量)字段。
-
正确设置针对索引和集合操作的权限
自动配置
|
There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the 升级说明以获取更多信息。 |
Spring AI提供Spring Boot自配置以供MongoDB Atlas向量库使用。
要使其启用,请在项目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 仓库。 |
向量存储实现可以初始化必要的模式,但您需要通过在文件的application.properties位置设置spring.ai.vectorstore.mongodb.initialize-schema=true来启用初始化。或者,您可以放弃初始化,通过MongoDB Atlas用户界面、Atlas行政API或Atlas CLI手动创建索引,这在需要高级映射或额外配置时非常有用。
| 这是一个破坏性变更!在早期版本的 Spring AI 中,此模式初始化是默认进行的。 |
请查看以下向量存储的配置参数列表,了解默认值和配置选项。这些配置参数的类型为C0。
此外,您还需要配置一个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'
}
创建一个 零 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 Vector Store的实现提供了一个通过 native MongoDB客户端(MongoClient)使用的1方法:
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
}
native client gives you access to MongoDB-specific features and operations that might not be exposed through the VectorStore interface.