Skip to content

Latest commit

 

History

History
55 lines (44 loc) · 1.35 KB

File metadata and controls

55 lines (44 loc) · 1.35 KB
endpoint scroll
lang java
es_version 9.3
client co.elastic.clients:elasticsearch-java:9.3.0

Elasticsearch 9.3 scroll endpoint (Java example)

Use client.scroll() to retrieve the next batch of results from a scrolling search. Start by calling search with a scroll parameter, then repeatedly call scroll until no more hits are returned:

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

var searchResp = client.search(s -> s
        .index("products")
        .scroll(t -> t.time("1m"))
        .size(2)
        .query(q -> q.matchAll(m -> m)),
    Product.class
);

var scrollId = searchResp.scrollId();
var hits = searchResp.hits().hits();

while (!hits.isEmpty()) {
    for (var hit : hits) {
        System.out.println(hit.id() + ": " + hit.source().name());
    }

    var scrollResp = client.scroll(sc -> sc
            .scrollId(scrollId)
            .scroll(t -> t.time("1m")),
        Product.class
    );

    scrollId = scrollResp.scrollId();
    hits = scrollResp.hits().hits();
}

Cleaning up

Always clear the scroll context when you are done to free server resources. Pass the last scroll ID you received:

client.clearScroll(c -> c.scrollId(scrollId));