Skip to main content

Elasticsearch

https://www.elastic.co/

Maven Dependency

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

APIs

The ElasticsearchEmbeddingStore comes with 2 implementations:

  • Using approximate kNN queries with the ElasticsearchConfigurationKnn configuration class (default).
  • Using scriptScore queries with the ElasticsearchConfigurationScript configuration class. Note that this implementation is using cosine similarity.

Common options

To create the ElasticsearchEmbeddingStore instance, you need to provide an Elasticsearch RestClient:

String apiKey = "VnVhQ2ZHY0JDZGJrU...";
RestClient restClient = RestClient
.builder(HttpHost.create("https://localhost:9200"))
.setDefaultHeaders(new Header[]{
new BasicHeader("Authorization", "ApiKey " + apiKey)
})
.build();

Note:

See the Elasticsearch documentation on how to create a RestClient instance.

Then you can create the embedding store. It uses the approximate kNN query implementation by default.

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

ElasticsearchConfigurationKnn configuration (default)

The previous is equivalent to:

ElasticsearchEmbeddingStore store = ElasticsearchEmbeddingStore.builder()
.configuration(ElasticsearchConfigurationKnn.builder().build())
.restClient(restClient)
.build();

ElasticsearchConfigurationScript configuration

If you want to use the previous, but slower behavior, you can use the ElasticsearchConfigurationScript configuration class:

ElasticsearchEmbeddingStore store = ElasticsearchEmbeddingStore.builder()
.configuration(ElasticsearchConfigurationScript.builder().build())
.restClient(restClient)
.build();

Examples