此版本仍在开发中,尚未被视为稳定版。如需最新的快照版本,请使用 Spring AI 1.1.3spring-doc.cadn.net.cn

MongoDB Atlas

本节将指导您设置 MongoDB Atlas 作为向量存储,以便与 Spring AI 一起使用。spring-doc.cadn.net.cn

什么是 MongoDB Atlas?

MongoDB Atlas 是 MongoDB 提供的完全托管的云数据库,可在 AWS、Azure 和 GCP 上使用。 Atlas 支持对 MongoDB 文档数据进行原生向量搜索和全文搜索。spring-doc.cadn.net.cn

MongoDB Atlas Vector Search 允许您将嵌入存储在 MongoDB 文档中,创建向量搜索索引,并使用近似最近邻算法(层次导航小世界)执行 KNN 搜索。 您可以在 MongoDB 聚合阶段中使用 $vectorSearch 聚合操作符对向量嵌入执行搜索。spring-doc.cadn.net.cn

前置条件

Auto-configuration

Spring AI自动配置和starter模块的artifact名称有了重大变化。 请参阅升级说明获取更多信息。spring-doc.cadn.net.cn

Spring AI 为 MongoDB Atlas 向量存储提供 Spring Boot 自动配置。 要启用它,请将以下依赖项添加到您项目的 Maven pom.xml 文件中:spring-doc.cadn.net.cn

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-vector-store-mongodb-atlas</artifactId>
</dependency>

或添加到您的 Gradle build.gradle 构建文件中:spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-vector-store-mongodb-atlas'
}
请参阅依赖管理部分,将Spring AI BOM添加到您的构建文件中。
请参阅 构件仓库 部分,将 Maven 中央仓库和/或快照仓库添加到您的构建文件中。

向量存储实现可以为您初始化所需的架构,但您必须通过在 application.properties 文件中设置 spring.ai.vectorstore.mongodb.initialize-schema=true 来选择加入。 或者,您可以选择退出初始化,并使用 MongoDB Atlas UI、Atlas Administration API 或 Atlas CLI 手动创建索引,这在索引需要高级映射或额外配置时可能很有用。spring-doc.cadn.net.cn

这是一个破坏性变更!在早期版本的 Spring AI 中,此架构初始化是默认发生的。

请查看 向量存储的配置参数 列表,以了解默认值和配置选项。spring-doc.cadn.net.cn

此外,您还需要一个已配置的 EmbeddingModel bean。有关更多信息,请参阅 EmbeddingModel 部分。spring-doc.cadn.net.cn

现在您可以在应用程序中将 MongoDBAtlasVectorStore 自动装配为向量存储:spring-doc.cadn.net.cn

@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-doc.cadn.net.cn

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.* 开头的属性用于配置 MongoDBAtlasVectorStorespring-doc.cadn.net.cn

<property> </property> <description> </description> 默认值

spring.ai.vectorstore.mongodb.initialize-schemaspring-doc.cadn.net.cn

是否初始化所需的模式spring-doc.cadn.net.cn

falsespring-doc.cadn.net.cn

spring.ai.vectorstore.mongodb.collection-namespring-doc.cadn.net.cn

存储向量的集合名称spring-doc.cadn.net.cn

vector_storespring-doc.cadn.net.cn

spring.ai.vectorstore.mongodb.index-namespring-doc.cadn.net.cn

向量搜索索引的名称spring-doc.cadn.net.cn

vector_indexspring-doc.cadn.net.cn

spring.ai.vectorstore.mongodb.path-namespring-doc.cadn.net.cn

向量存储的路径spring-doc.cadn.net.cn

embeddingspring-doc.cadn.net.cn

spring.ai.vectorstore.mongodb.metadata-fields-to-filterspring-doc.cadn.net.cn

可用于筛选的元数据字段的逗号分隔列表spring-doc.cadn.net.cn

空列表spring-doc.cadn.net.cn

手动配置

不使用 Spring Boot 自动配置,您可以手动配置 MongoDB Atlas 向量存储。为此,您需要在项目中添加 spring-ai-mongodb-atlas-storespring-doc.cadn.net.cn

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-mongodb-atlas-store</artifactId>
</dependency>

或添加到您的 Gradle build.gradle 构建文件中:spring-doc.cadn.net.cn

dependencies {
    implementation 'org.springframework.ai:spring-ai-mongodb-atlas-store'
}

创建一个 MongoTemplate bean:spring-doc.cadn.net.cn

@Bean
public MongoTemplate mongoTemplate() {
    return new MongoTemplate(MongoClients.create("<mongodb atlas connection string>"), "<database name>");
}

然后使用构建器模式创建 MongoDBAtlasVectorStore bean:spring-doc.cadn.net.cn

@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。spring-doc.cadn.net.cn

例如,您可以使用文本表达式语言:spring-doc.cadn.net.cn

vectorStore.similaritySearch(SearchRequest.builder()
        .query("The World")
        .topK(5)
        .similarityThreshold(0.7)
        .filterExpression("author in ['john', 'jill'] && article_type == 'blog'").build());

或以编程方式使用 Filter.Expression DSL:spring-doc.cadn.net.cn

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 过滤器表达式。

例如,此可移植的过滤器表达式:spring-doc.cadn.net.cn

author in ['john', 'jill'] && article_type == 'blog'

被转换为专有的 MongoDB Atlas 过滤器格式:spring-doc.cadn.net.cn

{
  "$and": [
    {
      "$or": [
        { "metadata.author": "john" },
        { "metadata.author": "jill" }
      ]
    },
    {
      "metadata.article_type": "blog"
    }
  ]
}

教程和代码示例

要开始使用 Spring AI 和 MongoDB:spring-doc.cadn.net.cn

访问原生客户端

MongoDB Atlas 向量存储的实现通过 getNativeClient() 方法提供对底层原生 MongoDB 客户端 (MongoClient) 的访问:spring-doc.cadn.net.cn

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 特定功能和操作。spring-doc.cadn.net.cn