Atlas Vector Search と spring AI を統合できます MongoDB Java Sync Driver を使用して生成系 AI アプリケーションをビルドします。このチュートリアルでは、spring AI のベクトル ストアとして Atlas Vector Search の使用を開始する方法と、データに対してセマンティック検索を実行する方法を説明します。
具体的には、次のアクションを実行します。
環境を設定します。
Atlas Vector Search インデックスの作成。
Atlas にベクトル埋め込みデータを保存します。
データに対してセマンティック検索クエリを実行します。
バックグラウンド
書込み AI は書込み保証を使用したアプリケーション フレーム ワーク です により、アプリケーションとさまざまな AI サービスとプラグインを組み合わせることができます。spring AI は、テキストベースのさまざまな AI ユースケースに使用できます。
Atlasをベクトル データベースとして使用し、 Atlas Vector Searchを使用してセマンティックで類似したドキュメントを検索することで RAGを実装できます。 RGRAG Atlas Vector Searchの詳細については、「 を使用した 検索拡張生成(RAG ) 」を してください。
前提条件
Atlas の サンプル データ セット からの映画データを含むコレクションを使用します。
Atlas アカウントで、MongoDB バージョン 6.0.11 または7.0.2 以降(RCs を含む)のクラスターを実行している。IP アドレスが Atlas プロジェクトのアクセスリストに含まれていることを確認してください。詳細については、クラスターの作成を参照してください。
OpenAI API キー。API リクエストに使用できるクレジットを持つ OpenAI アカウントが必要です。OpenAI アカウントの登録について詳しく知りたい場合は、 OpenAI API ウェブサイトをご覧ください。
Java 開発キット(JDK) バージョン8 以降。
Javaアプリケーション を設定して実行する環境。 Maven または Gradle を構成してプロジェクトを構築および実行するようにするには、IntelliJ IDEA や Eclipse IDE などの統合開発環境(IDE)を使用することをお勧めします。
環境を設定する
最初に、必要な依存関係の追加や構成プロパティの設定など、このチュートリアルの環境を設定する必要があります。
spring Java アプリケーションを作成します。
書込み保証 (write concern ) に移動する は、次の設定でプロジェクトを構成します。
プロジェクト: Maven
言語: Java
スキームを使用することで、選択したデフォルトのバージョンを使用できます。
プロジェクト メタデータ:
Java: 21
他のすべてのフィールドにデフォルト値を使用できます。
書込み初期化の右側にある [ ADD DEPENDENCIES ] をクリックし、次の依存関係を検索して追加します。
MongoDB Atlas Vector Database
Spring Data MongoDB
[GENERATE] をクリックして、Spring プロジェクトの zip バージョンをダウンロードします。ファイルを解凍し、IDE で開きます。
依存関係を追加します。
spring AI は、Atlas Vector Search のユーザー キー ステップの自動構成を提供します。
プロジェクトの
pom.xmlファイル内のdependencies配列に次の依存関係を追加します。 これらの依存関係により、spring AI と自動構成ライブラリがアプリケーションに追加されます。pom.xml<dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-openai-spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.ai</groupId> <artifactId>spring-ai-spring-boot-autoconfigure</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> 次に、
pom.xmlファイルにspring AI 請求書(BOM)のdependencyManagementエントリが含まれていることを確認します。重要
最新のspring AI 機能をアプリケーションに実装するには、spring AI BOM に使用される
spring-ai.version定数を1.0.0-SNAPSHOTに設定します。依存 マネジメント の詳細については、AIAI を参照してください。
最後に、spring AI スナップショットのリポジトリを
pom.xmlファイルのrepositoriesエントリに追加します。pom.xml<repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <releases> <enabled>false</enabled> </releases> </repository> これらのリポジトリの詳細については、「 マイルストーンとスナップショット リポジトリの追加AI 」を参照してください。 を参照してください。
pom.xmlファイルの編集が終了したら、プロジェクトを再読み込みして、依存関係がインストールされていることを確認します。
アプリケーション プロパティを定義します。
src/main/resources/application.properties ファイルを見つけ、そのファイルの内容を次のプロパティで置き換えます。 プレースホルダーを OpenAI APIキーとAtlas 接続文字列で置き換えます。
spring.application.name=springai-mongodb spring.ai.openai.api-key=<OpenAI API Key> spring.ai.openai.embedding.options.model=text-embedding-ada-002 spring.data.mongodb.uri=<connection string> spring.data.mongodb.database=springai_test spring.ai.vectorstore.mongodb.indexName=vector_index spring.ai.vectorstore.mongodb.collection-name=vector_store
注意
接続stringには、次の形式を使用する必要があります。
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net/?<settings>
接続文字列の取得の詳細については、「 Atlasを使い始める」チュートリアルを参照してください。
Atlas Vector Search インデックスの作成
ベクトル ストアでベクトル検索クエリを有効にするには、 springai_test.vector_storeコレクションに Atlas Vector Search インデックスを作成する必要があります。
スキーマの初期化を有効にします。
アプリケーションで Atlas をベクトル ストアとして構成すると、Spring AI はバックエンドスキーマを自動的に初期化できます。この初期化には、ベクトル埋め込みを含むコレクションに Atlas Vector Search インデックスを作成することが含まれます。
スキーマの初期化を有効にするため、次の設定を application.properties ファイルに追加します。
spring.ai.vectorstore.mongodb.initialize-schema=true
initialize-schema=true を指定すると、Spring AI はプログラムによってクラスター上に Atlas Vector Search インデックスを作成します。詳細については、「Atlas ベクトル検索インデックスの作成」を参照してください。
注意
既知の問題: 既存のインデックス
springai_test.vector_storeコレクションにvector_indexという既存の Atlas Vector Search インデックスがある場合、spring AI は追加のインデックスを作成しません。 このため、既存のインデックスが別の次元数など互換性のない設定で構成されていた場合は、チュートリアルの後半でエラーが発生する可能性があります。
インデックスが次の構成であることを確認します。
{ "fields": [ { "numDimensions": 1536, "path": "embedding", "similarity": "cosine", "type": "vector" } ] }
Atlas をベクトル ストアとして使用
このセクションでは、Atlas をベクトルデータベース(ベクトルストアとも呼ばれる)として構成し、カスタム データのベクトル埋め込みを保存できるようにする方法を説明します。
プロジェクトでsrc/main/java/com/example/demo/DemoApplication.javaファイルを見つけます。 このファイルと同じレベルで、 configというディレクトリを作成し、このディレクトリにConfig.javaというファイルを作成して、spring App 構成を設定します。
次の手順は、ベクトル ストアを準備するために必要なBeanオブジェクトを作成する方法を示しています。
インポート ステートメントを追加します。
次のコードをConfig.javaファイルに貼り付けて、必要なクラスをインポートします。
import org.springframework.ai.embedding.EmbeddingModel; import org.springframework.ai.openai.OpenAiEmbeddingModel; import org.springframework.ai.openai.api.OpenAiApi; import org.springframework.ai.vectorstore.MongoDBAtlasVectorStore; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.core.MongoTemplate;
参照アプリケーションのプロパティ。
次のコードをConfig.javaファイルに貼り付けて、アプリケーション プロパティ ファイルに設定した値を参照します。
public class Config { private String openAiKey; private String databaseName; private String collectionName; private String indexName; private String mongoUri; private Boolean initSchema; // Add beans here... }
VectorStore Spring Bean を作成します。
最後に、次のコードを貼り付けて、 VectorStoreインスタンスを返す Bearer を作成します。 VectorStoreインスタンスは、配置に対応するMongoTemplateと、前のステップで作成されたOpenAiEmbeddingModelを使用します。
public VectorStore mongodbVectorStore(MongoTemplate mongoTemplate, EmbeddingModel embeddingModel) { return new MongoDBAtlasVectorStore(mongoTemplate, embeddingModel, MongoDBAtlasVectorStore.MongoDBVectorStoreConfig.builder().build(), initSchema); }
カスタム データの保存とセマンティック検索クエリの実行
このセクションでは、Java アプリケーションでエンドポイントを作成して Atlas にカスタム データのベクトル埋め込みを保存し、そのデータに対してセマンティック検索クエリを実行する方法を学びます。
エンドポイントの作成
configフォルダーと同じレベルで、 controllerフォルダーを作成し、API エンドポイントを設定するためのController.javaファイルを作成します。 次の手順は、ベクトル ストアにデータを追加し、 similaritySearch()メソッドを使用してセマンティック検索クエリを実行するためのGETエンドポイントを作成する方法を示しています。
インポート ステートメントを追加します。
次のコードをController.javaファイルに貼り付けて、必要なクラスをインポートします。
import org.springframework.ai.document.Document; import org.springframework.ai.vectorstore.VectorStore; import org.springframework.ai.vectorstore.SearchRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; import java.util.stream.Collectors;
ベクトル ストアにドキュメントを追加するためのエンドポイントを作成します。
次のコードをコントローラーに貼り付けて、サンプル ドキュメントを作成し、それをベクトル埋め込みとしてベクトルストアに保存するGETエンドポイントを作成します。
public String addDocuments() { List<Document> docs = List.of( new Document("Proper tuber planting involves site selection, proper timing, and exceptional care. Choose spots with well-drained soil and adequate sun exposure. Tubers are generally planted in spring, but depending on the plant, timing varies. Always plant with the eyes facing upward at a depth two to three times the tuber's height. Ensure 4 inch spacing between small tubers, expand to 12 inches for large ones. Adequate moisture is needed, yet do not overwater. Mulching can help preserve moisture and prevent weed growth.", Map.of("author", "A", "type","post")), new Document("Successful oil painting necessitates patience, proper equipment, and technique. Begin with a carefully prepared, primed canvas. Sketch your composition lightly before applying paint. Use high-quality brushes and oils to create vibrant, long-lasting artworks. Remember to paint 'fat over lean,' meaning each subsequent layer should contain more oil to prevent cracking. Allow each layer to dry before applying another. Clean your brushes often and avoid solvents that might damage them. Finally, always work in a well-ventilated space.", Map.of("author", "A")), new Document("For a natural lawn, selection of the right grass type suitable for your climate is crucial. Balanced watering, generally 1 to 1.5 inches per week, is important; overwatering invites disease. Opt for organic fertilizers over synthetic versions to provide necessary nutrients and improve soil structure. Regular lawn aeration helps root growth and prevents soil compaction. Practice natural pest control and consider overseeding to maintain a dense sward, which naturally combats weeds and pest.", Map.of("author", "B", "type","post")) ); vectorStore.add(docs); return "Documents added successfully!\n"; }
セマンティック検索を実行するためのエンドポイントを作成します。
次のコードをコントローラーに貼り付けて、 "learn how to grow things"というフレーズのセマンティック検索クエリを実行し、最も関連性の高い結果を 2 つ返すGETエンドポイントを作成します。
1 2 public List<Map<String, Object>> searchDocuments() { 3 4 List<Document> results = vectorStore.similaritySearch( 5 SearchRequest 6 .query("learn how to grow things") 7 .withTopK(2) 8 ); 9 10 return results.stream().map(doc -> Map.of( 11 "content", doc.getContent(), 12 "metadata", doc.getMetadata() 13 )).collect(Collectors.toList()); 14 }
(任意)メタデータ フィルタリングを使用してセマンティック検索を実行します。
メタデータ フィルタリングを使用して検索を実行するには、 Java Sync Driverの Filter.Expression ビルダ クラスを使用できます。
MQLマッチ式を使用して、ドキュメントを事前にフィルタリングできます。 この例では、 authorフィールドの値が"A"であるドキュメントをフィルタリングします。 次に、 "learn how to grow things"というフレーズのセマンティック検索クエリを実行します。
searchDocuments()前のステップで定義されている メソッドの本体で、similaritySearch() メソッドを呼び出すコード(前のブロックの4 -8 行)を次のコードに置き換えます。
FilterExpressionBuilder b = new FilterExpressionBuilder(); List<Document> results = vectorStore.similaritySearch( SearchRequest.defaults() .withQuery("learn how to grow things") .withTopK(2) .withSimilarityThreshold(0.5) .withFilterExpression(b.eq("author", "A").build()) );
注意
メタデータ フィールドのパスを Atlas Vector Search インデックスに追加する必要があります。 詳細については、「 ベクトル検索のフィールドにインデックスを作成する方法 」チュートリアルの「 filter型について」セクションを参照してください。
メタデータの事前フィルタリングの詳細については、「 Atlas Vector Search の事前フィルター 」を参照してください。
アクセス エンドポイント
アプリケーションを実行すると、 エンドポイント にアクセスしてまずベクトル ストアにドキュメントを追加し、次にセマンティック検索クエリを実行できます。
ターミナル内からエンドポイントにアクセスします。
アプリケーションが実行されていることを確認したら、ターミナルで次のコマンドを実行してaddエンドポイントにアクセスします。これにより、サンプル データがベクトル埋め込みに変換され、Atlas に埋め込みが挿入されます。
curl -X GET http://localhost:8080/tutorial/add
Documents added successfully!
Tip
エンドポイントにアクセスした後、クラスター内のspringai_test.vector_storeコレクションに移動すると、Atlas UI でベクトル埋め込みを表示できます。
次に、ターミナルで次のコマンドを実行してsearchエンドポイントにアクセスし、セマンティック検索を実行します。
curl -X GET http://localhost:8080/tutorial/search
[{"content":"For a natural lawn, selection of the right grass type suitable for your climate is crucial. Balanced watering, generally 1 to 1.5 inches per week, is important; overwatering invites disease. Opt for organic fertilizers over synthetic versions to provide necessary nutrients and improve soil structure. Regular lawn aeration helps root growth and prevents soil compaction. Practice natural pest control and consider overseeding to maintain a dense sward, which naturally combats weeds and pest.","metadata":{"type":"post","author":"B"}},{"content":"Proper tuber planting involves site selection, proper timing, and exceptional care. Choose spots with well-drained soil and adequate sun exposure. Tubers are generally planted in spring, but depending on the plant, timing varies. Always plant with the eyes facing upward at a depth two to three times the tuber's height. Ensure 4 inch spacing between small tubers, expand to 12 inches for large ones. Adequate moisture is needed, yet do not overwater. Mulching can help preserve moisture and prevent weed growth.","metadata":{"type":"post","author":"A"}}]
次のステップ
このアプリの完了したバージョンを 表示およびダウンロードできますGithub .フルアプリを使用して、自分のアプリケーションのトラブルシューティングを行ったり、機能をすばやくテストしたりできます。
MongoDBは、次の開発者リソースも提供しています。