|
最新快照版本请使用Spring AI 1.1.0! |
MongoDB地图集
本节将带你了解如何将MongoDB图集作为向量存储器,以便配合Spring AI使用。
什么是MongoDB图谱?
MongoDB Atlas 是 MongoDB 提供的全托管云数据库,支持 AWS、Azure 和 GCP。Atlas 支持对 MongoDB 文档数据的原生向量搜索和全文搜索。
MongoDB Atlas 矢量搜索允许您将嵌入存储在 MongoDB 文档中,创建矢量搜索索引,并使用近似最近邻算法(分层可导航小世界)进行 KNN 搜索。您可以使用$vectorSearchMongoDB聚合阶段的聚合运算符用于对你的向量嵌入进行搜索。
自动配置
|
春季AI自动配置、起始模块的工件名称发生了重大变化。 更多信息请参阅升级说明。 |
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>
或者去你的Gradlebuild.gradle构建文件:
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-vector-store-mongodb-atlas'
}
| 请参考依赖管理部分,将Spring AI的物料清单添加到你的构建文件中。 |
| 请参阅“遗物仓库”部分,将Maven Central和/或快照仓库添加到你的构建文件中。 |
向量存储实现可以帮你初始化所需的模式,但你必须通过设置来选择加入spring.ai.vectorstore.mongodb.initialize-schema=true在application.properties文件。 或者,您也可以选择退出初始化,使用MongoDB Atlas UI、Atlas Administration API或Atlas CLI手动创建索引,如果索引需要高级映射或额外配置,这些功能非常有用。
| 这是一个颠覆性的变革!在早期版本的 Spring AI 中,这种模式初始化是默认的。 |
请查看矢量存储的配置参数列表,了解默认值和配置选项。
此外,你还需要一个配置嵌入模型豆。 更多信息请参阅嵌入模型部分。
现在你可以自动接线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:
| 属性 | 描述 | 默认值 |
|---|---|---|
|
是否初始化所需的模式 |
|
|
用于存储向量的集合名称 |
|
|
向量搜索索引的名称 |
|
|
存储向量的路径 |
|
|
可用于过滤的元数据字段列表,以逗号分隔 |
空列表 |
手动配置
你可以手动配置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构建文件:
dependencies {
implementation 'org.springframework.ai:spring-ai-mongodb-atlas-store'
}
创建一个Mongo模板豆:
@Bean
public MongoTemplate mongoTemplate() {
return new MongoTemplate(MongoClients.create("<mongodb atlas connection string>"), "<database name>");
}
然后创建MongoDBAtlasVectorStore使用构建图纸的豆子:
@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());
或者程序化地使用滤波。表达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图谱过滤表达式。 |
例如,这个可移植的Filter表达式:
author in ['john', 'jill'] && article_type == 'blog'
转换为专有的MongoDB图集过滤器格式:
{
"$and": [
{
"$or": [
{ "metadata.author": "john" },
{ "metadata.author": "jill" }
]
},
{
"metadata.article_type": "blog"
}
]
}
访问本地客户端
MongoDB Atlas 向量存储实现提供了对底层原生 MongoDB 客户端的访问(Mongo客户端)通过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接口。