跳到主要内容

Elasticsearch

https://www.elastic.co/

Maven依存関係​

<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-elasticsearch</artifactId>
<version>1.23.0-beta33</version>
</dependency>

概要​

langchain4j-elasticsearch モジュールは、埋め込みストアおよびコンテンツリトリーバーとしての Elasticsearch 連携を提供します。

主なクラスは次の 2 つです:

  • ElasticsearchEmbeddingStore:EmbeddingStore インターフェースの実装で、 Elasticsearch を使って埋め込みを保存・取得します。
  • ElasticsearchContentRetriever:ContentRetriever インターフェースの実装で、Elasticsearch のベクトル類似度検索により関連ドキュメントを取得します。

どちらのクラスも、Elasticsearch サーバーに接続するための Elasticsearch Client が必要です。

String apiKey = "VnVhQ2ZHY0JDZGJrU...";
ElasticsearchClient client = ElasticsearchClient.of(ec -> ec
.host("https://localhost:9200")
.apiKey(apiKey));

注意:

ElasticsearchClient インスタンスの作成方法については、 Elasticsearch ドキュメント を参照してください。

ElasticsearchEmbeddingStore​

ElasticsearchEmbeddingStore インスタンスを作成するには、ElasticsearchClient を渡します:

ElasticsearchEmbeddingStore store = ElasticsearchEmbeddingStore.builder()
.client(client)
.build();

次のオプションがあります:

  • indexName:使用する Elasticsearch インデックス名。デフォルトは default。
  • configuration:使用する ElasticsearchConfiguration。デフォルトは ElasticsearchConfigurationKnn。
  • refresh:ID を指定して書き込まれた、または削除されたドキュメントが検索で見えるようになるタイミング。デフォルトは Refresh.False。

上記のコードは次と同等です:

ElasticsearchEmbeddingStore store = ElasticsearchEmbeddingStore.builder()
.client(client)
.configuration(ElasticsearchConfigurationKnn.builder().build())
.indexName("default")
.build();

リフレッシュポリシー​

Elasticsearch は、書き込みリクエストが返った瞬間にドキュメントを検索可能にするわけではありません。デフォルトでは、 ドキュメントは次回の定期的なインデックスリフレッシュ(インデックスで別途指定されていない限り 1 秒に 1 回)で 検索可能になります。それまでの間、ドキュメントは安全に保存されており ID で取得できますが、検索結果には表示されません。

これは、ドキュメントを追加した直後にそれらを検索する処理を行う場合に重要になります。refresh オプションを使うと、 検索で見えるようになるまで待機できます:

import co.elastic.clients.elasticsearch._types.Refresh;

ElasticsearchEmbeddingStore store = ElasticsearchEmbeddingStore.builder()
.client(client)
.refresh(Refresh.WaitFor)
.build();

指定できる値は次の 3 つです:

  • Refresh.False(デフォルト)はドキュメントが保存された時点ですぐに返り、リフレッシュは Elasticsearch に任せます。 最も高速なオプションです。
  • Refresh.WaitFor はドキュメントが検索で見えるようになってから返ります。追加のリフレッシュを強制しないため、 検索可視性が必要な場合は通常これが適切な選択です。インデックスの自動リフレッシュが無効化されている場合 (index.refresh_interval: -1)、呼び出しは他の要因でリフレッシュが発生するまで待機することに注意してください。
  • Refresh.True は即座にリフレッシュを強制します。待機せずに可視性が得られますが、リクエストごとに新しいセグメントを 作成するとインデックス処理のスループットが低下するため、書き込みの多いインデックスでは避けてください。

このオプションは add、addAll、removeAll(Collection<String> ids) に適用されます。検索の動作は変わらず、 他のユーザーが同時に行った書き込みから自分を隔離するものでもありません。同じオプションは ElasticsearchContentRetriever.builder() でも利用できます。

フィルターによる削除(removeAll(Filter))は delete-by-query であるため、こちらもすでに検索で見える ドキュメントにしか一致しません。直前に追加された埋め込みが削除されずに残ることがあります。埋め込みを追加した直後に フィルターで削除する場合は、削除の実行前に書き込みが検索可能になるよう Refresh.WaitFor を設定してください。

詳細は Elasticsearch の refresh パラメータのドキュメント を参照してください。

埋め込みなしでのドキュメントの保存​

通常の add(Embedding, TextSegment) メソッドに加えて、このストアは埋め込みを計算せずにプレーンテキストだけを インデックスすることもできます:

store.add("Printer troubleshooting guide");                    // generates an id
store.add("my-id", "Printer troubleshooting guide"); // with your own id
store.addAllText(List.of("First guide", "Second guide")); // several at once

これらのドキュメントにはベクトルがないため、 ElasticsearchConfigurationKnn でも ElasticsearchConfigurationScript でも、ベクトル検索で返されることはありません。 全文検索では引き続き見つかるため、1 つのインデックスに埋め込み付きドキュメントとテキストのみのドキュメントの 両方を保持でき、 ElasticsearchConfigurationFullText または ElasticsearchConfigurationHybrid を使って両方の方法で検索できます。

ElasticsearchContentRetriever​

ContentRetriever には埋め込みモデルが必要です:

EmbeddingModel embeddingModel = new AllMiniLmL6V2QuantizedEmbeddingModel();

ElasticsearchContentRetriever インスタンスを作成するには、ElasticsearchClient と EmbeddingModel を渡します:

ElasticsearchContentRetriever contentRetriever = ElasticsearchContentRetriever.builder()
.client(client)
.embeddingModel(embeddingModel)
.build();

次のオプションがあります:

  • configuration:使用する ElasticsearchConfiguration(下記を参照)。デフォルトは ElasticsearchConfigurationKnn。
  • indexName:使用する Elasticsearch インデックス名。デフォルトは default。インデックスが存在しない場合は 自動的に作成されます。
  • maxResults:取得する結果の最大数。デフォルトは 3。
  • minScore:取得結果の最小スコアしきい値。デフォルトは 0.0。
  • filter:取得時に適用する Filter(ある場合)。デフォルトは null。

上記のコードは次と同等です:

ElasticsearchContentRetriever contentRetriever = ElasticsearchContentRetriever.builder()
.client(client)
.embeddingModel(embeddingModel)
.configuration(ElasticsearchConfigurationKnn.builder().build())
.indexName("default")
.maxResults(3)
.minScore(0.0)
.filter(null)
.build();

ElasticsearchConfiguration​

ElasticsearchConfiguration は、埋め込みストアまたはコンテンツリトリーバーが Elasticsearch サーバーとどのようにやり取りするかを定義します。ElasticsearchConfiguration インターフェースを実装して 独自の設定を作成することも、提供されている次の実装のいずれかを使用することもできます:

設定インスタンスを作成するには、各実装が提供するビルダーを使用できます。例:

ElasticsearchConfiguration configuration = ElasticsearchConfigurationKnn.builder().build();

ElasticsearchConfigurationKnn​

ElasticsearchConfigurationKnn は、近似 kNN クエリを使用してベクトル類似度検索を実行します。

ElasticsearchEmbeddingStore と ElasticsearchContentRetriever の両方で使用されるデフォルト設定です。

インスタンスを作成するには、ビルダーを使用できます:

ElasticsearchConfiguration configuration = ElasticsearchConfigurationKnn.builder().build();

次のオプションがあります:

  • numCandidates:検索時に考慮する候補近傍の数。デフォルトは null で、Elasticsearch の デフォルト値を使用することを意味します。
  • includeVectorResponse:検索レスポンスにベクトルフィールドを含めるかどうか。デフォルトは false。

注意: Elasticsearch サーバーのバージョン 9.2 以降では、ベクトルフィールドはデフォルトでレスポンスから除外されます。 レスポンスにベクトルフィールドを含めるには(非推奨)、ビルダーで includeVectorResponse を設定します:

ElasticsearchConfigurationKnn configuration = ElasticsearchConfigurationKnn.builder()
.includeVectorResponse(true)
.build();

ElasticsearchConfigurationScript​

ElasticsearchConfigurationScript は、scriptScore クエリを使用してベクトル類似度検索を実行します。この 実装はコサイン類似度を使用することに注意してください。

ElasticsearchEmbeddingStore と ElasticsearchContentRetriever の両方で利用できます。

インスタンスを作成するには、ビルダーを使用できます:

ElasticsearchConfiguration configuration = ElasticsearchConfigurationScript.builder().build();

次のオプションがあります:

  • includeVectorResponse:検索レスポンスにベクトルフィールドを含めるかどうか。デフォルトは false。

注意: Elasticsearch サーバーのバージョン 9.2 以降では、ベクトルフィールドはデフォルトでレスポンスから除外されます。 レスポンスにベクトルフィールドを含めるには(非推奨)、ビルダーで includeVectorResponse を設定します:

ElasticsearchConfiguration configuration = ElasticsearchConfigurationScript.builder()
.includeVectorResponse(true)
.build();

ElasticsearchConfigurationFullText​

ElasticsearchConfigurationFullText は、全文検索を使用して関連ドキュメントを取得します。

ElasticsearchContentRetriever でのみ利用できます。

インスタンスを作成するには、ビルダーを使用できます:

ElasticsearchConfiguration configuration = ElasticsearchConfigurationFullText.builder().build();

ElasticsearchConfigurationHybrid​

ElasticsearchConfigurationHybrid は、ハイブリッド検索を使用して kNN ベクトルクエリと全文クエリを組み合わせます。 ハイブリッド検索には Elasticsearch のエンタープライズライセンスまたはトライアルが必要であることに注意してください。

ElasticsearchContentRetriever でのみ利用できます。

インスタンスを作成するには、ビルダーを使用できます:

ElasticsearchConfiguration configuration = ElasticsearchConfigurationHybrid.builder().build();

次のオプションがあります:

  • numCandidates:検索時に考慮する候補近傍の数。デフォルトは null で、Elasticsearch の デフォルト値を使用することを意味します。
  • includeVectorResponse:検索レスポンスにベクトルフィールドを含めるかどうか。デフォルトは false。

注意: Elasticsearch サーバーのバージョン 9.2 以降では、ベクトルフィールドはデフォルトでレスポンスから除外されます。 レスポンスにベクトルフィールドを含めるには(非推奨)、ビルダーで includeVectorResponse を設定します:

ElasticsearchConfiguration configuration = ElasticsearchConfigurationHybrid.builder()
.includeVectorResponse(true)
.build();

カスタム設定の作成​

ElasticsearchConfiguration インターフェースを実装して、独自の Elasticsearch 設定を作成できます。例:

public class MyElasticsearchConfiguration implements ElasticsearchConfiguration {
@Override
SearchResponse<Document> vectorSearch(
ElasticsearchClient client,
String indexName,
EmbeddingSearchRequest embeddingSearchRequest) {
// Your optional custom vector search implementation here
}

@Override
SearchResponse<Document> fullTextSearch(
ElasticsearchClient client,
String indexName,
FullTextSearchRequest request) {
// Your optional custom full text search implementation here
}

@Override
SearchResponse<Document> hybridSearch(
ElasticsearchClient client,
String indexName,
EmbeddingSearchRequest embeddingSearchRequest,
String textQuery) {
// Your optional custom hybrid search implementation here
}
}

ユースケースに関連するメソッドだけを実装すればよいことに注意してください:

  • vectorSearch:ベクトル類似度検索用(ElasticsearchEmbeddingStore と ElasticsearchContentRetriever の両方で使用)。
  • fullTextSearch:全文検索用(ElasticsearchContentRetriever のみで使用)。
  • hybridSearch:ハイブリッド検索用(ElasticsearchContentRetriever のみで使用)。

FullTextSearchRequest は、検索対象の textQuery と、ElasticsearchContentRetriever に設定された maxResults、minScore、filter を保持しています。これらを適用する責任は実装側にあり、 適用しないとフィルターに一致しないドキュメントが返される可能性があります。

注意: 非推奨の fullTextSearch(ElasticsearchClient client, String indexName, String textQuery) メソッドもあります。 そのメソッドのみを実装している設定は引き続き動作しますが、リトリーバーの maxResults、minScore、filter は 無視され、警告がログに出力されます。代わりに FullTextSearchRequest を受け取るメソッドを実装してください。

例​