| endpoint | search |
|---|---|
| lang | java |
| es_version | 9.3 |
| client | co.elastic.clients:elasticsearch-java:9.3.0 |
Use client.search() to find documents matching a query.
public record Product(String name, String brand, double price,
String category,
@JsonProperty("in_stock") boolean inStock,
double rating) {}
var response = client.search(s -> s
.index("products")
.query(q -> q
.match(m -> m.field("category").query("electronics"))
)
.sort(so -> so.field(f -> f.field("price").order(SortOrder.Asc))),
Product.class
);
System.out.println("Found " + response.hits().total().value() + " products");
for (var hit : response.hits().hits()) {
var doc = hit.source();
System.out.println(" " + doc.name() + " — $" + doc.price());
}Use from and size to paginate through results:
int page = 0;
int pageSize = 10;
var response = client.search(s -> s
.index("products")
.query(q -> q.matchAll(m -> m))
.from(page * pageSize)
.size(pageSize)
.sort(so -> so.field(f -> f.field("price").order(SortOrder.Desc))),
Product.class
);For deep pagination beyond 10,000 results, use searchAfter with
a point-in-time instead.
Use aggregations to compute summary statistics alongside search
results. Set size(0) when you only need the aggregation:
var response = client.search(s -> s
.index("products")
.size(0)
.aggregations("by_category", a -> a
.terms(t -> t.field("category.keyword"))
.aggregations("avg_price", sub -> sub
.avg(av -> av.field("price"))
)
),
Void.class
);
for (var bucket : response.aggregations().get("by_category").sterms().buckets().array()) {
var avg = bucket.aggregations().get("avg_price").avg().value();
System.out.printf(" %s: %d products, avg $%.2f%n",
bucket.key().stringValue(), bucket.docCount(), avg);
}