MongoDB Atlas

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

什麼是 MongoDB Atlas?

MongoDB Atlas 是 MongoDB 在 AWS、Azure 和 GCP 上提供的完全託管的雲資料庫。Atlas 支援對您的 MongoDB 文件資料進行原生向量搜尋和全文搜尋。

MongoDB Atlas 向量搜尋 允許您將嵌入儲存在 MongoDB 文件中,建立向量搜尋索引,並使用近似最近鄰演算法(分層可導航小世界)執行 KNN 搜尋。您可以在 MongoDB 聚合階段使用 $vectorSearch 聚合運算子對您的向量嵌入執行搜尋。

先決條件

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

  • 一個執行中且已啟用向量搜尋的 MongoDB Atlas 例項

  • 已配置向量搜尋索引的集合

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

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

自動配置

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

或新增到您的 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 管理 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

是否初始化所需的模式

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

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

空列表

手動配置

您可以透過手動配置 MongoDB Atlas 向量儲存,而不是使用 Spring Boot 自動配置。為此,您需要將 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 特定功能和操作。

© . This site is unofficial and not affiliated with VMware.