Qdrant

このセクションでは、ドキュメントの埋め込みを保存し、類似性検索を実行するための Qdrant VectorStore のセットアップについて説明します。

Qdrant (英語) は、オープンソースの高性能ベクトル検索エンジン / データベースです。効率的な k-NN 検索操作のために HNSW (階層型ナビゲート可能スモールワールド) アルゴリズムを使用し、メタデータベースのクエリに高度なフィルタリング機能を提供します。

前提条件

  • Qdrant インスタンス: Qdrant ドキュメントのインストール (英語) 手順に従って、Qdrant インスタンスをセットアップします。

  • 必要に応じて、EmbeddingModel が QdrantVectorStore によって保存される埋め込みを生成するための API キー。

Qdrant コレクションは、適切なディメンションと構成を使用して事前に作成する (英語) ことをお勧めします。コレクションが作成されていない場合、QdrantVectorStore は、Cosine の類似性と構成された EmbeddingModel のディメンションを使用してコレクションを作成しようとします。

自動構成

Spring AI 自動構成、スターターモジュールのアーティファクト名に大きな変更がありました。詳細については、アップグレードノートを参照してください。

Spring AI は、Qdrant ベクトルストア用の Spring Boot 自動構成を提供します。これを有効にするには、プロジェクトの Maven pom.xml ファイルに次の依存関係を追加します。

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-vector-store-qdrant</artifactId>
</dependency>

または、Gradle build.gradle ビルドファイルに保存します。

dependencies {
    implementation 'org.springframework.ai:spring-ai-starter-vector-store-qdrant'
}
Spring AI BOM をビルドファイルに追加するには、"依存関係管理" セクションを参照してください。

デフォルト値と構成オプションについては、ベクトルストアの構成パラメーターのリストを参照してください。

リポジトリセクションを参照して、ビルドファイルに Maven Central リポジトリやスナップショットリポジトリを追加します。

ベクトルストアの実装では必要なスキーマを初期化できますが、ビルダーで initializeSchema ブール値を指定するか、application.properties ファイルで …​initialize-schema=true を設定することによってオプトインする必要があります。

これは重大な変更です。Spring AI の以前のバージョンでは、このスキーマの初期化はデフォルトで行われていました。

さらに、設定済みの EmbeddingModel Bean が必要です。詳細については、"EmbeddingModel" セクションを参照してください。

これで、QdrantVectorStore をアプリケーション内のベクトルストアとして自動接続できるようになりました。

@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 Qdrant
vectorStore.add(documents);

// Retrieve documents similar to a query
List<Document> results = vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build());

プロパティの構成

Qdrant に接続して QdrantVectorStore を使用するには、インスタンスのアクセス詳細を提供する必要があります。Spring Boot の application.yml を介して簡単な構成を提供できます。

spring:
  ai:
    vectorstore:
      qdrant:
        host: <qdrant host>
        port: <qdrant grpc port>
        api-key: <qdrant api key>
        collection-name: <collection name>
        use-tls: false
        initialize-schema: true
        batching-strategy: TOKEN_COUNT # Optional: Controls how documents are batched for embedding

spring.ai.vectorstore.qdrant.* で始まるプロパティは、QdrantVectorStore を構成するために使用されます。

プロパティ 説明 デフォルト値

spring.ai.vectorstore.qdrant.host

Qdrant サーバーのホスト

localhost

spring.ai.vectorstore.qdrant.port

Qdrant サーバーの gRPC ポート

6334

spring.ai.vectorstore.qdrant.api-key

認証に使用する API キー

-

spring.ai.vectorstore.qdrant.collection-name

使用するコレクションの名前

vector_store

spring.ai.vectorstore.qdrant.use-tls

TLS(HTTPS) を使用するかどうか

false

spring.ai.vectorstore.qdrant.initialize-schema

スキーマを初期化するかどうか

false

spring.ai.vectorstore.qdrant.batching-strategy

埋め込みを計算するときにドキュメントをバッチ処理する戦略。オプションは TOKEN_COUNT または FIXED_SIZE です

TOKEN_COUNT

手動構成

Spring Boot の自動構成を使用する代わりに、Qdrant ベクトルストアを手動で構成できます。そのためには、プロジェクトに spring-ai-qdrant-store を追加する必要があります。

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-qdrant-store</artifactId>
</dependency>

または、Gradle build.gradle ビルドファイルに保存します。

dependencies {
    implementation 'org.springframework.ai:spring-ai-qdrant-store'
}
Spring AI BOM をビルドファイルに追加するには、"依存関係管理" セクションを参照してください。

Qdrant クライアント Bean を作成します。

@Bean
public QdrantClient qdrantClient() {
    QdrantGrpcClient.Builder grpcClientBuilder =
        QdrantGrpcClient.newBuilder(
            "<QDRANT_HOSTNAME>",
            <QDRANT_GRPC_PORT>,
            <IS_TLS>);
    grpcClientBuilder.withApiKey("<QDRANT_API_KEY>");

    return new QdrantClient(grpcClientBuilder.build());
}

次に、ビルダーパターンを使用して QdrantVectorStore Bean を作成します。

@Bean
public VectorStore vectorStore(QdrantClient qdrantClient, EmbeddingModel embeddingModel) {
    return QdrantVectorStore.builder(qdrantClient, embeddingModel)
        .collectionName("custom-collection")     // Optional: defaults to "vector_store"
        .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")));
}

メタデータフィルタリング

Qdrant ストアでは、汎用的でポータブルなメタデータフィルターも活用できます。

例: 次のいずれかのテキスト式言語を使用できます。

vectorStore.similaritySearch(
    SearchRequest.builder()
        .query("The World")
        .topK(TOP_K)
        .similarityThreshold(SIMILARITY_THRESHOLD)
        .filterExpression("author in ['john', 'jill'] && article_type == 'blog'").build());

または、Filter.Expression DSL を使用してプログラム的に次のようにします。

FilterExpressionBuilder b = new FilterExpressionBuilder();

vectorStore.similaritySearch(SearchRequest.builder()
    .query("The World")
    .topK(TOP_K)
    .similarityThreshold(SIMILARITY_THRESHOLD)
    .filterExpression(b.and(
        b.in("author", "john", "jill"),
        b.eq("article_type", "blog")).build()).build());
これらの (ポータブル) フィルター式は、独自の Qdrant フィルター (英語) 式に自動的に変換されます。

ネイティブクライアントへのアクセス

Qdrant ベクトルストアの実装は、getNativeClient() メソッドを通じて、基盤となるネイティブ Qdrant クライアント (QdrantClient) へのアクセスを提供します。

QdrantVectorStore vectorStore = context.getBean(QdrantVectorStore.class);
Optional<QdrantClient> nativeClient = vectorStore.getNativeClient();

if (nativeClient.isPresent()) {
    QdrantClient client = nativeClient.get();
    // Use the native client for Qdrant-specific operations
}

ネイティブクライアントを使用すると、VectorStore インターフェースでは公開されない可能性のある Qdrant 固有の機能や操作にアクセスできます。