MongoDB Atlas

本節將引導您設定 MongoDB Atlas 作為向量儲存,以便與 Spring AI 一起使用。

什麼是 MongoDB Atlas?

MongoDB Atlas 是 MongoDB 提供的全託管雲資料庫,可在 AWS、Azure 和 GCP 上使用。Atlas 支援對您的 MongoDB 文件資料進行原生的向量搜尋 (Vector Search) 和全文搜尋 (full text search)。

MongoDB Atlas 向量搜尋 (Vector Search) 允許您將嵌入 (embeddings) 儲存在 MongoDB 文件中,建立向量搜尋索引 (vector search indexes),並使用近似最近鄰演算法 (approximate nearest neighbor algorithm,層狀可導航小世界,HNSW) 執行 KNN 搜尋。您可以在 MongoDB 聚合階段 (aggregation stage) 中使用 $vectorSearch 聚合運算子 (aggregation operator) 對您的向量嵌入進行搜尋。

前提條件

  • 一個執行 MongoDB 6.0.11、7.0.2 或更高版本的 Atlas 叢集。要開始使用 MongoDB Atlas,您可以按照此處的說明進行操作。確保您的 IP 地址已包含在您的 Atlas 專案的訪問列表中

  • 啟用了向量搜尋的執行中的 MongoDB Atlas 例項

  • 配置了向量搜尋索引的集合 (Collection)

  • 包含 id (字串)、content (字串)、metadata (文件) 和 embedding (向量) 欄位的集合模式 (Collection schema)

  • 索引和集合操作的適當訪問許可權

自動配置

Spring AI 自動配置、啟動器模組的 artifact 名稱發生了重大變化。有關更多資訊,請參閱升級說明

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>

或新增到您的 Gradle build.gradle 構建檔案中

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-vector-store-mongodb-atlas'
}
請參閱依賴管理部分,以將 Spring AI BOM 新增到您的構建檔案中。
請參閱倉庫部分,以將 Maven Central 和/或 Snapshot 倉庫新增到您的構建檔案中。

向量儲存實現可以為您初始化所需的模式,但您必須透過在 application.properties 檔案中設定 spring.ai.vectorstore.mongodb.initialize-schema=true 來選擇啟用此功能。或者,您可以選擇停用初始化,並使用 MongoDB Atlas UI、Atlas Administration API 或 Atlas CLI 手動建立索引,如果索引需要高階對映或其他配置,這會很有用。

這是一項重大變更!在早期版本的 Spring AI 中,此模式初始化是預設啟用的。

請查看向量儲存的配置引數列表,瞭解預設值和配置選項。

此外,您還需要一個配置好的 EmbeddingModel bean。有關更多資訊,請參閱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.ai.vectorstore.mongodb.initialize-schema

是否初始化所需模式

false

spring.ai.vectorstore.mongodb.collection-name

用於儲存向量的集合名稱

vector_store

spring.ai.vectorstore.mongodb.index-name

向量搜尋索引的名稱

vector_index

spring.ai.vectorstore.mongodb.path-name

儲存向量的路徑

embedding

spring.ai.vectorstore.mongodb.metadata-fields-to-filter

可用於過濾的元資料欄位列表(逗號分隔)

空列表

手動配置

您可以在不使用 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'
}

建立一個 MongoTemplate 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

訪問原生客戶端

MongoDB Atlas 向量儲存實現透過 getNativeClient() 方法提供對底層原生 MongoDB 客戶端 (MongoClient) 的訪問

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 特定功能和操作。