MongoDB Atlas
このセクションでは、Spring AI で使用するベクトルストアとして MongoDB Atlas を設定する手順について説明します。
MongoDB Atlas とは何ですか ?
MongoDB Atlas (英語) は、AWS、Azure、GCP で利用できる MongoDB の完全マネージド型クラウドデータベースです。Atlas は、MongoDB ドキュメントデータに対するネイティブベクトル検索と全文検索をサポートしています。
MongoDB Atlas ベクトル検索 (英語) を使用すると、MongoDB ドキュメントに埋め込みを保存し、ベクトル検索インデックスを作成し、近似最近傍アルゴリズム (階層型ナビゲート可能なスモールワールド) を使用して KNN 検索を実行できます。MongoDB 集計ステージで $vectorSearch
集計演算子を使用して、ベクトル埋め込みの検索を実行できます。
前提条件
MongoDB バージョン 6.0.11、7.0.2 以降を実行している Atlas クラスター。MongoDB Atlas の使用を開始するには、ここ (英語) の手順に従ってください。IP アドレスが Atlas プロジェクトのアクセスリスト (英語) に含まれていることを確認してください。
ベクトル検索が有効になっている実行中の MongoDB Atlas インスタンス
ベクトル検索インデックスが設定されたコレクション
ID (文字列)、コンテンツ (文字列)、メタデータ (ドキュメント)、埋め込み (ベクトル) フィールドを含むコレクションスキーマ
インデックスおよびコレクション操作に対する適切なアクセス権限
自動構成
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'
}
Spring AI BOM をビルドファイルに追加するには、"依存関係管理" セクションを参照してください。 |
リポジトリセクションを参照して、ビルドファイルに Maven Central リポジトリやスナップショットリポジトリを追加します。 |
ベクトルストアの実装では必要なスキーマを初期化できますが、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
vector-index-name: custom_vector_index
path-name: custom_embedding
metadata-fields-to-filter: author,year
spring.ai.vectorstore.mongodb.*
で始まるプロパティは、MongoDBAtlasVectorStore
を構成するために使用されます。
プロパティ | 説明 | デフォルト値 |
---|---|---|
| 必要なスキーマを初期化するかどうか |
|
| ベクトルを保存するコレクションの名前 |
|
| ベクトル検索インデックスの名前 |
|
| ベクトルが保存されるパス |
|
| フィルタリングに使用できるメタデータフィールドのカンマ区切りリスト | 空のリスト |
手動構成
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 の使用を開始するには:
Spring AI 統合の入門ガイド (英語) を参照してください。
Spring AI と MongoDB を使用した Retrieval Augmented Generation (RAG) を示す包括的なコード例については、この詳細なチュートリアル (英語) を参照してください。
ネイティブクライアントへのアクセス
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 固有の機能と操作にアクセスできます。