Basic features

Updated at:

The Lindorm vector engine supports vector data retrieval and scalar, vector, and full-text hybrid search. Use the Java High Level REST Client for standard operations, or the Java Low Level REST Client when you need to call the _plugins API directly.

Prerequisites

Before you begin, ensure that you have:

Overview

Working with vector search involves these steps:

  1. Install the Java High Level REST Client — add Maven dependencies to your project.

  2. Connect to the search engine — configure the endpoint, port, and credentials.

  3. Create a vector index — choose HNSW, IVFPQ, or sparse vector, and define the index mappings.

  4. Write data — index single documents, batch documents, or sparse vectors.

  5. (Optional) Build an index offline — use the Low Level REST Client to call the _plugins API for offline index construction.

  6. Query data — run pure vector queries or hybrid queries that combine vector and scalar filters.

Set up the client

Install the Java High Level REST Client

Add the following dependencies to the dependencies section of your pom.xml:

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.10.0</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.20.0</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.20.0</version>
</dependency>

Connect to the search engine

// The Elasticsearch-compatible endpoint for the Lindorm search engine.
String search_url = "ld-t4n5668xk31ui****-proxy-search-public.lindorm.rds.aliyuncs.com";
int search_port = 30070;

String username = "user";
String password = "test";
final CredentialsProvider credentials_provider = new BasicCredentialsProvider();
credentials_provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));


RestHighLevelClient highClient = new RestHighLevelClient(
  RestClient.builder(new HttpHost( search_url, search_port, "http")).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
      return httpClientBuilder.setDefaultCredentialsProvider(credentials_provider);
    }
  })
);

Connection parameters

Parameter Description
search_url The Elasticsearch-compatible endpoint for the search engine. To get the endpoint, see Elasticsearch-compatible address. Use the VPC address when connecting over a VPC, or the Internet address when connecting over the public network.
search_port 30070 — the port for the Elasticsearch Compatibility feature on the Lindorm search engine.
username The username for the search engine. To get the default credentials, go to Database Connections in the left navigation pane, click the Search Engine tab, and view the credentials.
password The password for the search engine. Same location as username.
Important

For applications deployed on an ECS instance, connect over a VPC for higher security and lower network latency. For on-premises applications, enable the public endpoint first: go to Database Connections > Search Engine tab, then click Enable Public Endpoint in the upper-right corner.

Create a vector index

The Lindorm vector engine supports three index types: HNSW for dense vectors, IVFPQ for large-scale approximate search, and sparse vector for sparse representations.

The Map.of syntax in the following examples requires JDK 9 or later. For earlier JDK versions, replace Map.of(...) with explicit HashMap construction.

HNSW index

HNSW (Hierarchical Navigable Small World) provides high recall with low latency for dense vector search. Set engine to lvector and name to hnsw.

String indexName = "vector_hnsw_test";

CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
{
  // Create settings
  Map<String, Object> indexMap = new HashMap<>();
  indexMap.put("number_of_shards", 2);
  indexMap.put("knn", true);
  Map<String, Object> settings = new HashMap<>();
  settings.put("index", indexMap);
  createIndexRequest.settings(settings);
}

{
  // Create mappings
  Map<String, Object> source = new HashMap<>();
  source.put("excludes", new String[] { "vector1" });

  // Create a map for "method.parameters"
  Map<String, Object> parameters = new HashMap<>();
  parameters.put("m", 24);
  parameters.put("ef_construction", 500);

  // Create a map for "method"
  Map<String, Object> method = new HashMap<>();
  method.put("engine", "lvector");
  method.put("name", "hnsw");
  method.put("space_type", "l2");
  method.put("parameters", parameters);

  // Create a map for "vector1"
  Map<String, Object> vector1 = new HashMap<>();
  vector1.put("type", "knn_vector");
  vector1.put("dimension", 3);
  vector1.put("method", method);

  // Create a map for the properties
  Map<String, Object> properties = new HashMap<>();
  properties.put("vector1", vector1);
  properties.put("field1", Map.of("type", "long"));

  // Create the mappings map
  Map<String, Object> mappings = new HashMap<>();
  mappings.put("_source", source);
  mappings.put("properties", properties);
  createIndexRequest.mapping(mappings);
}

CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
System.out.println("createIndexResponse: " + createIndexResponse);

HNSW index parameters

Parameter Required Description
engine Yes Set to lvector to use the Lindorm vector engine.
name Yes Set to hnsw for the HNSW algorithm.
space_type No The distance metric. Valid values: l2 (Euclidean distance), cosinesimil (cosine similarity).
m No The number of bidirectional links created per element. Higher values improve recall but increase memory usage.
ef_construction No The size of the dynamic list during graph construction. Higher values improve graph quality but slow indexing.

HNSW query-time tuning

Parameter Valid values Description
ef_search [1, 1000] The length of the dynamic candidate list during search. Higher values improve recall at the cost of search speed. Default: 100.

IVFPQ index

IVFPQ (Inverted File with Product Quantization) is suited for large-scale vector datasets. It uses offline index construction and requires knn.offline.construction: true.

String indexName = "vector_ivfpq_test";

CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
{
  // Create settings
  Map<String, Object> indexMap = new HashMap<>();
  indexMap.put("number_of_shards", 2);
  indexMap.put("knn", true);
  indexMap.put("knn.offline.construction", true);
  Map<String, Object> settings = new HashMap<>();
  settings.put("index", indexMap);
  createIndexRequest.settings(settings);
}

{
  // Create mappings
  Map<String, Object> source = new HashMap<>();
  source.put("excludes", new String[] { "vector1" });

  Map<String, Object> properties = new HashMap<>();
  int dim = 3;

  // Vector1 property
  Map<String, Object> vector1 = new HashMap<>();
  vector1.put("type", "knn_vector");
  vector1.put("dimension", dim);
  vector1.put("data_type", "float");

  Map<String, Object> method = new HashMap<>();
  method.put("engine", "lvector");
  method.put("name", "ivfpq");
  method.put("space_type", "cosinesimil");

  Map<String, Object> parameters = new HashMap<>();
  parameters.put("m", dim);
  parameters.put("nlist", 10000);
  parameters.put("centroids_use_hnsw", true);
  parameters.put("centroids_hnsw_m", 48);
  parameters.put("centroids_hnsw_ef_construct", 500);
  parameters.put("centroids_hnsw_ef_search", 200);
  method.put("parameters", parameters);

  vector1.put("method", method);
  properties.put("vector1", vector1);

  // Field1 property
  Map<String, Object> field1 = new HashMap<>();
  field1.put("type", "long");
  properties.put("field1", field1);

  Map<String, Object> mappings = new HashMap<>();
  mappings.put("_source", source);
  mappings.put("properties", properties);
  createIndexRequest.mapping(mappings);
}

CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
System.out.println("createIndexResponse: " + createIndexResponse);

IVFPQ index parameters

Parameter Required Description
engine Yes Set to lvector.
name Yes Set to ivfpq.
space_type No The distance metric. Valid values: l2, cosinesimil, innerproduct.
m Yes The number of subvectors for product quantization. Typically set to the vector dimension.
nlist Yes The number of cluster centroids. A higher value improves recall but increases memory and build time.
centroids_use_hnsw No Set to true to build centroids using HNSW for faster centroid search.
centroids_hnsw_m No The HNSW m parameter for centroid graph construction.
centroids_hnsw_ef_construct No The ef_construction value for centroid HNSW graph building.
centroids_hnsw_ef_search No The ef_search value for centroid lookup during indexing.

IVFPQ query-time tuning

Parameter Valid values Default Description
nprobe [1, nlist] — The number of cluster centroids to search. Higher values improve recall but reduce search performance. When nlist is 10000, start with 60 and increase in steps to 80, 100, 120, 140, or 160 to improve recall.
reorder_factor [1, 200] 10 Reranks the top k * reorder_factor candidates using original vectors to compensate for quantization precision loss. Set to 1 when k is greater than 100; set to 5 when k is small.

Sparse vector index

Use a sparse vector index when your vectors have a high proportion of zero values, such as in text retrieval with sparse embeddings.

String indexName = "vector_sparse_test";

CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
{
  // Create settings
  Map<String, Object> indexMap = new HashMap<>();
  indexMap.put("number_of_shards", 2);
  indexMap.put("knn", true);
  Map<String, Object> settings = new HashMap<>();
  settings.put("index", indexMap);
  createIndexRequest.settings(settings);
}

{
  // Create mappings
  Map<String, Object> source = new HashMap<>();
  source.put("excludes", new String[]{"vector1"});

  Map<String, Object> properties = new HashMap<>();

  Map<String, Object> vector1 = new HashMap<>();
  vector1.put("type", "knn_vector");
  vector1.put("data_type", "sparse_vector");

  Map<String, Object> method = new HashMap<>();
  method.put("engine", "lvector");
  method.put("name", "sparse_hnsw");
  method.put("space_type", "innerproduct");

  Map<String, Object> parameters = new HashMap<>();
  parameters.put("m", 24);
  parameters.put("ef_construction", 200);
  method.put("parameters", parameters);

  vector1.put("method", method);

  properties.put("vector1", vector1);

  Map<String, Object> field1 = new HashMap<>();
  field1.put("type", "long");
  properties.put("field1", field1);

  Map<String, Object> mappings = new HashMap<>();
  mappings.put("_source", source);
  mappings.put("properties", properties);
  createIndexRequest.mapping(mappings);
}

CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
System.out.println("createIndexResponse: " + createIndexResponse);

Write data

Writing to an index with a vector field works the same as writing to a regular index, except for the vector field format.

Write a single document

Map<String, Object> fieldMap = new HashMap<>();
fieldMap.put("field1", 1);
fieldMap.put("vector1", new float[]{1.2f,1.3f,1.4f});
IndexRequest indexRequest = new IndexRequest("vector_test");
indexRequest.id("1");
indexRequest.source(fieldMap);
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);

Write documents in batches

Use BulkRequest to combine inserts, updates, and deletes in a single request:

BulkRequest bulkRequest = new BulkRequest();
{
  Map<String, Object> fieldMap = new HashMap<>();
  fieldMap.put("field1", 1);
  fieldMap.put("vector1", new float[]{2.2f,2.3f,2.4f});
  IndexRequest indexRequest = new IndexRequest("vector_test");
  indexRequest.id("1");
  indexRequest.source(fieldMap);
  bulkRequest.add(indexRequest);
}
{
  Map<String, Object> fieldMap = new HashMap<>();
  fieldMap.put("field1", 1);
  fieldMap.put("vector1", new float[]{2.2f,2.3f,2.4f});
  IndexRequest indexRequest = new IndexRequest("vector_test");
  indexRequest.id("2");
  indexRequest.source(fieldMap);
  bulkRequest.add(indexRequest);
}
{
  Map<String, Object> fieldMap = new HashMap<>();
  fieldMap.put("field1", 2);
  fieldMap.put("vector1", new float[]{1.2f,1.3f,4.4f});
  IndexRequest indexRequest = new IndexRequest("vector_test");
  indexRequest.id("3");
  indexRequest.source(fieldMap);
  bulkRequest.add(indexRequest);
}
{
  DeleteRequest deleteRequest = new DeleteRequest("vector_test", "2");
  bulkRequest.add(deleteRequest);
}
{
  Map<String, Object> fieldMap = new HashMap<>();
  fieldMap.put("field1", 3);
  fieldMap.put("vector1", new float[]{2.2f,3.3f,4.4f});
  UpdateRequest updateRequest = new UpdateRequest();
  updateRequest.index("vector_test");
  updateRequest.id("1");
  updateRequest.doc(fieldMap);
  bulkRequest.add(updateRequest);
}
BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);

Write a sparse vector

For sparse vectors, represent vector1 as a map with indices and values lists instead of a float array:

Map<String, Object> vectorMap = new HashMap<>();
vectorMap.put("indices", Lists.of(10, 12, 16));
vectorMap.put("values", Lists.of(1.2, 1.3, 1.4));

Map<String, Object> fieldMap = new HashMap<>();
fieldMap.put("field1", 1);
fieldMap.put("vector1", vectorMap);

IndexRequest indexRequest = new IndexRequest("vector_test");
indexRequest.id("1");
indexRequest.source(fieldMap);
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);

Build an index

The Java High Level REST Client does not directly support all custom plugin APIs. Use the Low Level REST Client to call the _plugins API for offline index construction. For details, see Build an index.

Query data

All query examples use the LVectorExtBuilder class to pass custom search parameters via the ext field. Define this class once in your project:

package com.aliyun.lindorm;

import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.search.SearchExtBuilder;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

public class LVectorExtBuilder extends SearchExtBuilder {

  final Map<String, String> searchParams;
  protected final String name;

  public LVectorExtBuilder(String name, Map<String, String> searchParams) {
    this.name = name;
    this.searchParams = searchParams;
  }

  @Override
  public void writeTo(StreamOutput out) throws IOException {
    out.writeMap(searchParams, StreamOutput::writeString, StreamOutput::writeString);
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    LVectorExtBuilder that = (LVectorExtBuilder) o;
    return Objects.equals(searchParams, that.searchParams) && Objects.equals(name, that.name);
  }

  @Override
  public int hashCode() {
    return Objects.hash(searchParams, name);
  }

  @Override
  public String getWriteableName() {
    return name;
  }

  @Override
  public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    builder.startObject(name);
    for (Map.Entry<String, String> searchParam : searchParams.entrySet()) {
      builder.field(searchParam.getKey(), searchParam.getValue());
    }
    builder.endObject();
    return builder;
  }
}

Query pure vector data

Submit a k-NN query with a target vector and the number of nearest neighbors to return (k). Use the lvector ext block to pass tuning parameters.

float[] vectors = new float[]{2.2f,3.3f,4.4f};
SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
Map<String, Object> queryBody = new HashMap<>();
{
  Map<String, Object> vectorMap = new HashMap<>();
  vectorMap.put("vector", vectors);
  vectorMap.put("k", topK);
  queryBody.put("knn", Map.of(vectorColumn, vectorMap));
}
searchSourceBuilder.query(QueryBuilders.wrapperQuery(new Gson().toJson(queryBody)));
Map<String, String> ext = Map.of("min_score", "0.8");
searchSourceBuilder.ext(Collections.singletonList(new LVectorExtBuilder("lvector", ext)));
searchRequest.source(searchSourceBuilder);
searchRequest.indices(index);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(searchResponse);

Query parameters

Location Parameter Required Description
knn vector Yes The query vector.
k Yes The number of nearest neighbors to return.
ext.lvector min_score No The similarity threshold. Only vectors with a score above this value are returned. Valid values: [0, +inf). Default: 0.
filter_type No The hybrid query filter mode. Valid values: pre_filter, post_filter, efficient_filter. Default: efficient_filter.
ef_search No The dynamic candidate list length for HNSW search. Applies only to HNSW indexes. Valid values: [1, 1000]. Default: 100.
nprobe No The number of cluster centroids to search. Applies only to IVFPQ indexes. Valid values: [1, nlist].
reorder_factor No The reranking proportion for IVFPQ, computed as k * reorder_factor. Applies only to IVFPQ indexes. Valid values: [1, 200]. Default: 10.

Return specific fields

To return only selected fields, pass a FetchSourceContext with the field names. To return all non-vector fields, set fetchSource to true.

SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
Map<String, Object> queryBody = new HashMap<>();
{
  Map<String, Object> vectorMap = new HashMap<>();
  vectorMap.put("vector", vectors);
  vectorMap.put("k", topK);
  queryBody.put("knn", Map.of(vectorColumn, vectorMap));
}
searchSourceBuilder.query(QueryBuilders.wrapperQuery(new Gson().toJson(queryBody)));
Map<String, String> ext = Map.of("min_score", "0.8");
searchSourceBuilder.ext(Collections.singletonList(new LVectorExtBuilder("lvector", ext)));
// Return only field1 and field2
searchSourceBuilder.fetchSource(new FetchSourceContext(true, new String[]{"field1", "field2"}, null));
searchRequest.source(searchSourceBuilder);
searchRequest.indices(index);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(searchResponse);

Query with HNSW tuning

Use ef_search in the lvector ext block to control the recall-latency tradeoff at query time:

SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
Map<String, Object> queryBody = new HashMap<>();
{
  Map<String, Object> vectorMap = new HashMap<>();
  vectorMap.put("vector", vectors);
  vectorMap.put("k", topK);
  queryBody.put("knn", Map.of(vectorColumn, vectorMap));
}
searchSourceBuilder.query(QueryBuilders.wrapperQuery(new Gson().toJson(queryBody)));
Map<String, String> ext = Map.of("ef_search", "100");
searchSourceBuilder.ext(Collections.singletonList(new LVectorExtBuilder("lvector", ext)));
searchSourceBuilder.fetchSource(new FetchSourceContext(true, new String[]{"field1", "field2"}, null));
searchRequest.source(searchSourceBuilder);
searchRequest.indices(index);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(searchResponse);

Query with IVFPQ tuning

Use nprobe and reorder_factor to balance recall rate against search performance:

SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
Map<String, Object> queryBody = new HashMap<>();
{
  Map<String, Object> vectorMap = new HashMap<>();
  vectorMap.put("vector", vectors);
  vectorMap.put("k", topK);
  queryBody.put("knn", Map.of(vectorColumn, vectorMap));
}
searchSourceBuilder.query(QueryBuilders.wrapperQuery(new Gson().toJson(queryBody)));
Map<String, String> ext = Map.of("nprobe", "60", "reorder_factor", "5");
searchSourceBuilder.ext(Collections.singletonList(new LVectorExtBuilder("lvector", ext)));
searchSourceBuilder.fetchSource(new FetchSourceContext(true, new String[]{"field1", "field2"}, null));
searchRequest.source(searchSourceBuilder);
searchRequest.indices(index);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(searchResponse);
Important

When nlist is 10000, start with nprobe = 60. To improve recall, increase nprobe to 80, 100, 120, 140, or 160. This has far less performance overhead than increasing reorder_factor. Set reorder_factor to 1 when k is greater than 100.

Query a sparse vector

For sparse vector queries, pass vector1 as a map with indices and values instead of a float array:

SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
Map<String, Object> queryBody = new HashMap<>();
{
  Map<String, Object> knn = new HashMap<>();
  Map<String, Object> vector1 = new HashMap<>();
  vector1.put("vector", new HashMap<String, Object>() {{
    put("indices", Arrays.asList(10, 45, 16));
    put("values", Arrays.asList(0.5, 0.5, 0.2));
  }});
  vector1.put("k", 10);
  knn.put("vector1", vector1);
  queryBody.put("knn", knn);
}
searchSourceBuilder.query(QueryBuilders.wrapperQuery(new Gson().toJson(queryBody)));
searchRequest.source(searchSourceBuilder);
searchRequest.indices(index);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(searchResponse);

Hybrid query

Combine a k-NN vector query with scalar field filters to narrow results. The vector engine supports three filter strategies:

Strategy When the filter runs Constraint Recommended for
pre_filter Before vector search 10,000-record limit on filtered set High-selectivity filters with small result sets
post_filter After vector search Increase k to compensate for post-filtering Most use cases; typically yields more similar results
efficient_filter Automatically chosen None Default — let the engine decide

Pre-filter query

Add a filter inside the knn query block and set filter_type to pre_filter. The engine filters structured data first, then searches within the filtered set.

Pre-filter mode supports a maximum of 10,000 records in the filtered set.
SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

// vectorColumn is the name of the vector field.
// field1 is the name of the attribute column.
Map<String, Object> queryBody = Map.of("knn", Map.of(vectorColumn, Map.of(
  "vector", vectors,
  "k", topK,
  "filter", Map.of("range", Map.of("filed1", Map.of("gte", 0))))));
searchSourceBuilder.query(QueryBuilders.wrapperQuery(new Gson().toJson(queryBody)));
Map<String, String> ext = Map.of("filter_type", "pre_filter");
searchSourceBuilder.ext(Collections.singletonList(new LVectorExtBuilder("lvector", ext)));
searchRequest.source(searchSourceBuilder);
searchRequest.indices("vector_test");
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(searchResponse);

Post-filter query

Set filter_type to post_filter to retrieve vector results first, then apply scalar filters. Increase k to ensure enough candidates remain after filtering.

SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

// vectorColumn is the name of the vector field.
// field1 is the name of the attribute column.
Map<String, Object> queryBody = Map.of("knn", Map.of(vectorColumn, Map.of(
  "vector", vectors,
  "k", topK,
  "filter", Map.of("range", Map.of("filed1", Map.of("gte", 0))))));
searchSourceBuilder.query(QueryBuilders.wrapperQuery(new Gson().toJson(queryBody)));
Map<String, String> ext = Map.of("filter_type", "post_filter");
searchSourceBuilder.ext(Collections.singletonList(new LVectorExtBuilder("lvector", ext)));
searchRequest.source(searchSourceBuilder);
searchRequest.indices("vector_test");
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(searchResponse);

For IVFPQ indexes, add nprobe and reorder_factor to the ext block:

Map<String, String> ext = Map.of("filter_type", "post_filter", "nprobe", "60", "reorder_factor", "1");
Important

In post-filter mode, set k up to 10,000 (maximum 20,000) to keep latency under 100 milliseconds. Set reorder_factor to 1 when k is large. When nlist is 10000, start with nprobe = 60 and increase to 80, 100, 120, 140, or 160 to improve recall.

You can also apply the post-filter outside the k-NN query block using the postFilter method:

SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

// vectorColumn is the name of the vector field.
Map<String, Object> queryBody = Map.of("knn", Map.of(vectorColumn, Map.of(
  "vector", vectors,
  "k", topK)));
searchSourceBuilder.query(QueryBuilders.wrapperQuery(new Gson().toJson(queryBody)));

// Apply filter after vector retrieval: field1 >= 0
searchSourceBuilder.postFilter(QueryBuilders.rangeQuery("field1").gte(0));

searchRequest.source(searchSourceBuilder);
searchRequest.indices(index);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(searchResponse);

Common operations

Use the Low Level REST Client for index management operations not covered by the High Level REST Client.

  • List all indexes with their data volumes:

    Request request = new Request("GET", "/_cat/indices?v");
    Response response = restClient.performRequest(request);
    String responseBody = EntityUtils.toString(response.getEntity());
    System.out.println(responseBody);
  • Get the document count for a specific index:

    CountRequest countRequest = new CountRequest(index);
    CountResponse countResponse = client.count(countRequest, RequestOptions.DEFAULT);
    System.out.println(countResponse.getCount());
  • Get index settings and mappings:

    GetIndexRequest getIndexRequest = new GetIndexRequest(index);
    GetIndexResponse getIndexResponse = client.indices().get(getIndexRequest, RequestOptions.DEFAULT);
    getIndexResponse.getMappings().forEach((k, v) -> System.out.println(k + " " + v.getSourceAsMap()));
    getIndexResponse.getSettings().forEach((k, v) -> System.out.println(k + " " + v));
  • Delete an index:

    DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);
    AcknowledgedResponse deleteIndexResponse = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
    System.out.println("deleteIndexResponse: " + deleteIndexResponse.isAcknowledged());
  • Delete documents by query:

    DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(index);
    deleteByQueryRequest.setQuery(QueryBuilders.termQuery("field1", "1"));
    BulkByScrollResponse bulkByScrollResponse = client.deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT);
    System.out.println(bulkByScrollResponse.getTotal());