MongoDB Atlas
本节将引导您将 MongoDB Atlas 设置为矢量存储以用于 Spring AI。
什么是 MongoDB Atlas?
MongoDB Atlas 是 MongoDB 提供的完全托管式云数据库,可在 AWS、Azure 和 GCP 中使用。 Atlas 支持对 MongoDB 文档数据进行原生矢量搜索和全文搜索。
MongoDB Atlas Vector Search 允许您将嵌入存储在 MongoDB 文档中,创建向量搜索索引,并使用近似最近邻算法(分层可导航小世界)执行 KNN 搜索。
您可以使用$vectorSearch
aggregation 运算符来对向量嵌入执行搜索。
自动配置
Spring AI 为 MongoDB Atlas Vector Store 提供 Spring Boot 自动配置。
要启用它,请将以下依赖项添加到项目的 Maven 中pom.xml
文件:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-mongodb-atlas-store-spring-boot-starter</artifactId>
</dependency>
或发送到您的 Gradlebuild.gradle
build 文件:
dependencies {
implementation 'org.springframework.ai:spring-ai-mongodb-atlas-store-spring-boot-starter'
}
请参阅 Dependency Management 部分,将 Spring AI BOM 添加到您的构建文件中。 |
请参阅 Repositories 部分,将 Maven Central 和/或 Snapshot Repositories 添加到您的构建文件中。 |
vector store 实现可以为您初始化必要的架构,但您必须通过设置spring.ai.vectorstore.mongodb.initialize-schema=true
在application.properties
文件。
或者,您也可以选择退出初始化并使用 MongoDB Atlas UI、Atlas 管理 API 或 Atlas CLI 手动创建索引,如果索引需要高级映射或其他配置,这可能很有用。
这是一个突破性的变化!在早期版本的 Spring AI 中,默认情况下会进行此架构初始化。 |
请查看 vector store 的配置参数列表,了解默认值和配置选项。
此外,您还需要配置一个EmbeddingModel
豆。请参阅 EmbeddingModel 部分以了解更多信息。
现在,您可以自动连接MongoDBAtlasVectorStore
作为应用程序中的 vector store 中:
@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
vector-index-name: custom_vector_index
path-name: custom_embedding
metadata-fields-to-filter: author,year
属性以spring.ai.vectorstore.mongodb.*
用于配置MongoDBAtlasVectorStore
:
财产 | 描述 | 默认值 |
---|---|---|
|
是否初始化所需的 schema |
|
|
用于存储向量的集合的名称 |
|
|
向量搜索索引的名称 |
|
|
存储向量的路径 |
|
|
可用于筛选的元数据字段的逗号分隔列表 |
空列表 |
手动配置
您可以手动配置 MongoDB Atlas 向量存储,而不是使用 Spring Boot 自动配置。为此,您需要添加spring-ai-mongodb-atlas-store
到您的项目:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-mongodb-atlas-store</artifactId>
</dependency>
或发送到您的 Gradlebuild.gradle
build 文件:
dependencies {
implementation 'org.springframework.ai:spring-ai-mongodb-atlas-store'
}
创建一个MongoTemplate
豆:
@Bean
public MongoTemplate mongoTemplate() {
return new MongoTemplate(MongoClients.create("<mongodb atlas connection string>"), "<database name>");
}
然后创建MongoDBAtlasVectorStore
使用 Builder 模式的 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) 的综合代码示例,请参阅此详细教程。
访问 Native Client
MongoDB Atlas Vector Store 实现提供对底层原生 MongoDB 客户端 (MongoClient
) 通过getNativeClient()
方法:
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
接口。