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 專案的 https://www.mongodb.com/docs/atlas/security/ip-access-list/#std-label-access-list[存取清單]中。

  • 用於計算文件嵌入的 EmbeddingModel 實例。有多種選項可供選擇。請參閱 EmbeddingModel 章節以取得更多資訊。

  • 用於設定和執行 Java 應用程式的環境。

自動組態

Spring AI 為 MongoDB Atlas 向量儲存區提供 Spring Boot 自動組態。若要啟用它,請將下列依賴項新增至您專案的 Maven pom.xml 檔案

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

或您的 Gradle build.gradle 組建檔案。

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

向量儲存區實作可以為您初始化必要的結構描述,但您必須透過在適當的建構函式中指定 initializeSchema 布林值,或在 application.properties 檔案中設定 …​initialize-schema=true 來選擇加入。

請參閱 依賴項管理 章節,將 Spring AI BOM 新增至您的組建檔案。
請參閱 儲存庫 章節,將 Milestone 和/或 Snapshot 儲存庫新增至您的組建檔案。

結構描述初始化

向量儲存區實作可以為您初始化必要的結構描述,但您必須透過在適當的建構函式中指定 initializeSchema 布林值,或在 application.properties 檔案中設定 spring.ai.vectorstore.mongodb.initialize-schema=true 來選擇加入。

這是一個重大變更!在較早版本的 Spring AI 中,此結構描述初始化預設會發生。

initializeSchema 設定為 true 時,會自動執行下列動作

  • 集合建立:如果指定的用於儲存向量的集合尚不存在,則會建立該集合。

  • 搜尋索引建立:將根據組態屬性建立搜尋索引。

如果您執行的是免費或共用層級叢集,您必須透過 Atlas UI、Atlas Administration API 或 Atlas CLI 單獨建立索引。

如果您在 springai_test.vector_store collection 集合上已有一個名為 vector_index 的 Atlas 向量搜尋索引,Spring AI 將不會建立額外的索引。因此,如果現有索引是以不相容的設定 (例如不同的維度數量) 組態,您稍後可能會遇到錯誤。

請確保您的索引具有下列組態

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

此外,您將需要一個已組態的 EmbeddingModel Bean。請參閱 EmbeddingModel 章節以取得更多資訊。

以下是所需 Bean 的範例

@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.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-name

用於儲存向量的集合名稱。

vector_store

spring.ai.vectorstore.mongodb.initialize-schema

是否為您初始化後端結構描述

false

spring.ai.vectorstore.mongodb.path-name

用於儲存向量的路徑名稱。

embedding

spring.ai.vectorstore.mongodb.indexName

用於儲存向量的索引名稱。

vector_index

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

以逗號分隔的值,指定查詢向量儲存區時,哪些中繼資料欄位可用於篩選。需要此項,以便在中繼資料索引尚不存在時建立它們

空清單

手動組態屬性

如果您偏好手動組態 MongoDB Atlas 向量儲存區而不安裝自動組態,您可以直接設定 MongoDBAtlasVectorStore 及其依賴項來完成。

組態範例

@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);
    }
}

屬性

  • collectionName:用於儲存向量的集合名稱。

  • vectorIndexName:向量索引的名稱。

  • pathName:向量儲存的路徑。

  • metadataFieldsToFilter:要篩選的中繼資料欄位清單。

您可以透過在 MongoDBAtlasVectorStore 建構函式中將 true 作為最後一個參數傳遞來啟用結構描述初始化

新增文件

若要將文件新增至向量儲存區,您需要將輸入文件轉換為 Document 類型,並呼叫 addDocuments() 方法。此方法將使用 EmbeddingModel 計算嵌入,並將其儲存到 MongoDB 集合中。

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 集合中移除對應的文件。

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

vectorStore.delete(ids);

若要執行相似性搜尋,請建構具有所需查詢參數的 SearchRequest 物件,並呼叫 similaritySearch() 方法。此方法將傳回符合基於向量相似性的查詢的文件清單。

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

中繼資料篩選

中繼資料篩選允許透過基於指定中繼資料欄位篩選結果來進行更精細的查詢。此功能使用 MongoDB Query API 來執行與向量搜尋結合的篩選操作。

篩選運算式

MongoDBAtlasFilterExpressionConverter 類別會將篩選運算式轉換為 MongoDB Atlas 中繼資料篩選運算式。支援的運算包括

  • $and

  • $or

  • $eq

  • $ne

  • $lt

  • $lte

  • $gt

  • $gte

  • $in

  • $nin

這些運算啟用篩選邏輯,以應用於與向量儲存區中文件相關聯的中繼資料欄位。

篩選運算式範例

以下是如何在相似性搜尋中使用篩選運算式的範例

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