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 搜索。 您可以使用$vectorSearchaggregation 运算符来对向量嵌入执行搜索。spring-doc.cadn.net.cn

先决条件

  • 运行 MongoDB 版本 6.0.11、7.0.2 或更高版本的 Atlas 集群。要开始使用 MongoDB Atlas,您可以按照此处的说明进行作。确保您的 IP 地址包含在 Atlas 项目的 https://www.mongodb.com/docs/atlas/security/ip-access-list/#std-label-access-list[访问列表] 中。spring-doc.cadn.net.cn

  • EmbeddingModel实例来计算文档嵌入。有几个选项可用。请参阅 EmbeddingModel 部分以了解更多信息。spring-doc.cadn.net.cn

  • 用于设置和运行 Java 应用程序的环境。spring-doc.cadn.net.cn

自动配置

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

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

或发送到您的 Gradlebuild.gradlebuild 文件。spring-doc.cadn.net.cn

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

矢量存储实现可以为您初始化必要的架构,但您必须通过指定initializeSchemaboolean 或设置…​initialize-schema=trueapplication.properties文件。spring-doc.cadn.net.cn

请参阅 Dependency Management 部分,将 Spring AI BOM 添加到您的构建文件中。
请参阅 Repositories 部分,将 Milestone 和/或 Snapshot Repositories 添加到您的构建文件中。

Schema 初始化

矢量存储实现可以为您初始化必要的架构,但您必须通过指定initializeSchemaboolean 或设置spring.ai.vectorstore.mongodb.initialize-schema=trueapplication.properties文件。spring-doc.cadn.net.cn

这是一个突破性的变化!在早期版本的 Spring AI 中,默认情况下会进行此架构初始化。

什么时候initializeSchema设置为true,将自动执行以下作:spring-doc.cadn.net.cn

如果您运行的是免费或共享层集群,则必须通过 Atlas UI、Atlas 管理 API 或 Atlas CLI 单独创建索引。spring-doc.cadn.net.cn

如果您有一个名为vector_indexspringai_test.vector_store collection,Spring AI 不会创建额外的索引。因此,如果现有索引配置了不兼容的设置(例如维度数不同),您稍后可能会遇到错误。

确保您的索引具有以下配置:spring-doc.cadn.net.cn

{
  "fields": [
    {
      "numDimensions": 1536,
      "path": "embedding",
      "similarity": "cosine",
      "type": "vector"
    }
  ]
}

此外,您还需要配置一个EmbeddingModel豆。请参阅 EmbeddingModel 部分以了解更多信息。spring-doc.cadn.net.cn

以下是所需 bean 的示例:spring-doc.cadn.net.cn

@Bean
public EmbeddingModel embeddingModel() {
    // Can be any other EmbeddingModel implementation.
    return new OpenAiEmbeddingModel(new OpenAiApi(System.getenv("SPRING_AI_OPENAI_API_KEY")));
}

配置属性

您可以在 Spring Boot 配置中使用以下属性来自定义 MongoDB Atlas 矢量存储。spring-doc.cadn.net.cn

...
spring.data.mongodb.uri=<connection string>
spring.data.mongodb.database=<database name>

spring.ai.vectorstore.mongodb.collection-name=vector_store
spring.ai.vectorstore.mongodb.initialize-schema=true
spring.ai.vectorstore.mongodb.path-name=embedding
spring.ai.vectorstore.mongodb.indexName=vector_index
spring.ai.vectorstore.mongodb.metadata-fields-to-filter=foo
财产 描述 默认值

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

是否为您初始化后端 Schemaspring-doc.cadn.net.cn

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

用于存储向量的索引的名称。spring-doc.cadn.net.cn

vector_indexspring-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

手动配置属性

如果您希望手动配置 MongoDB Atlas 向量存储而不进行自动配置,则可以直接设置MongoDBAtlasVectorStore及其依赖项。spring-doc.cadn.net.cn

示例配置

@Configuration
public class VectorStoreConfig {

    @Bean
    public MongoDBAtlasVectorStore vectorStore(MongoTemplate mongoTemplate, EmbeddingModel embeddingModel) {
        MongoDBVectorStoreConfig config = MongoDBVectorStoreConfig.builder()
            .withCollectionName("custom_vector_store")
            .withVectorIndexName("custom_vector_index")
            .withPathName("custom_embedding_path")
            .withMetadataFieldsToFilter(List.of("author", "year"))
            .build();

        return new MongoDBAtlasVectorStore(mongoTemplate, embeddingModel, config, true);
    }
}

性能

您可以通过将true作为MongoDBAtlasVectorStore构造 函数spring-doc.cadn.net.cn

添加文档

要将文档添加到 vector store,您需要将输入文档转换为Document键入并调用addDocuments()方法。此方法将使用EmbeddingModel以计算嵌入并将其保存到 MongoDB 集合中。spring-doc.cadn.net.cn

List<Document> docs = List.of(
	new Document("Proper tuber planting involves site selection, timing, and care. Choose well-drained soil and adequate sun exposure. Plant in spring, with eyes facing upward at a depth two to three times the tuber's height. Ensure 4-12 inch spacing based on tuber size. Adequate moisture is needed, but avoid overwatering. Mulching helps preserve moisture and prevent weeds.", Map.of("author", "A", "type", "post")),
	new Document("Successful oil painting requires patience, proper equipment, and technique. Prepare a primed canvas, sketch lightly, and use high-quality brushes and oils. Paint 'fat over lean' to prevent cracking. Allow each layer to dry before applying the next. Clean brushes often and work in a well-ventilated space.", Map.of("author", "A")),
	new Document("For a natural lawn, select the right grass type for your climate. Water 1 to 1.5 inches per week, avoid overwatering, and use organic fertilizers. Regular aeration helps root growth and prevents compaction. Practice natural pest control and overseeding to maintain a dense lawn.", Map.of("author", "B", "type", "post")) );

vectorStore.add(docs);

删除文档

要从向量存储中删除文档,请使用delete()方法。此方法采用文档 ID 列表,并从 MongoDB 集合中删除相应的文档。spring-doc.cadn.net.cn

List<String> ids = List.of("id1", "id2", "id3"); // Replace with actual document IDs

vectorStore.delete(ids);

要执行相似性搜索,请构造一个SearchRequest对象,并调用similaritySearch()方法。此方法将根据向量相似性返回与查询匹配的文档列表。spring-doc.cadn.net.cn

List<Document> results = vectorStore.similaritySearch(
            SearchRequest
                    .query("learn how to grow things")
                    .withTopK(2)
    );

元数据筛选

元数据筛选允许通过根据指定的元数据字段筛选结果来进行更精细的查询。此功能使用 MongoDB 查询 API 与矢量搜索一起执行筛选作。spring-doc.cadn.net.cn

筛选表达式

MongoDBAtlasFilterExpressionConverter类将筛选表达式转换为 MongoDB Atlas 元数据筛选表达式。支持的作包括:spring-doc.cadn.net.cn

这些作允许将筛选逻辑应用于与向量存储中的文档关联的元数据字段。spring-doc.cadn.net.cn

筛选表达式示例

以下是如何在相似性搜索中使用筛选条件表达式的示例:spring-doc.cadn.net.cn

FilterExpressionBuilder b = new FilterExpressionBuilder();

List<Document> results = vectorStore.similaritySearch(
        SearchRequest.defaults()
                .withQuery("learn how to grow things")
                .withTopK(2)
                .withSimilarityThreshold(0.5)
                .withFilterExpression(this.b.eq("author", "A").build())
);

教程和代码示例

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