Skip to content

Latest commit

 

History

History
74 lines (61 loc) · 1.98 KB

File metadata and controls

74 lines (61 loc) · 1.98 KB
endpoint async_search
lang java
es_version 9.3
client co.elastic.clients:elasticsearch-java:9.3.0

Elasticsearch 9.3 async_search endpoint (Java example)

Use client.asyncSearch().submit() to start a search that runs in the background. This is useful for long-running queries that would otherwise time out:

public record Product(String name, String brand, double price,
                      String category,
                      @JsonProperty("in_stock") boolean inStock,
                      double rating) {}

var response = client.asyncSearch().submit(s -> s
        .index("products")
        .waitForCompletionTimeout(t -> t.time("0s"))
        .query(q -> q.matchAll(m -> m)),
    Product.class
);

var searchId = response.id();
System.out.println("Search submitted: " + searchId.substring(0, 20) + "...");

Polling for completion

Check the status of an async search, then retrieve the results once complete:

while (true) {
    var status = client.asyncSearch().status(st -> st.id(searchId));
    if (!status.isRunning()) break;
    Thread.sleep(500);
}

var result = client.asyncSearch().get(g -> g.id(searchId), Product.class);
for (var hit : result.response().hits().hits()) {
    System.out.println("  " + hit.source().name());
}

Cleanup

Always delete the async search when done to free server resources. Use try/finally to ensure cleanup even if processing fails:

var response = client.asyncSearch().submit(s -> s
        .index("products")
        .waitForCompletionTimeout(t -> t.time("0s"))
        .query(q -> q.match(m -> m.field("category").query("electronics"))),
    Product.class
);
var searchId = response.id();

try {
    var result = client.asyncSearch().get(
        g -> g.id(searchId).waitForCompletionTimeout(t -> t.time("10s")),
        Product.class
    );
    for (var hit : result.response().hits().hits()) {
        System.out.println(hit.source().name());
    }
} finally {
    client.asyncSearch().delete(d -> d.id(searchId));
}