I have a problem to write range query for elastic search running on Docker in my Spring Boot example.
I tried to write RangeQuery but I cannot implement it in elasticsearchClient.search.
How can I do that?
Here is the code snippet shown below
public List<Item> searchItemsByPriceRange(double minPrice, double maxPrice) throws IOException {
RangeQuery rangeQuery = new RangeQuery.Builder()
.field("price") // Specify the field name here
.gte(JsonData.of(minPrice)) // Greater than or equal to minPrice
.lte(JsonData.of(maxPrice)) // Less than or equal to maxPrice
.build();
log.info("Elasticsearch query: {}", rangeQuery.toString());
SearchResponse<Item> response = elasticsearchClient.search(q ->
q.index("itemindex").query(rangeQuery), Item.class);
log.info("Elasticsearch response: {}", response.toString());
return extractItemsFromResponse(response);
}
private List<Item> extractItemsFromResponse(SearchResponse<Item> response) {
return response
.hits()
.hits()
.stream()
.map(Hit::source)
.collect(Collectors.toList());
}
Here is the problem part
SearchResponse<Item> response = elasticsearchClient.search(q ->
q.index("itemindex").query(rangeQuery), Item.class);
Cannot resolve method 'query(RangeQuery)'
You need the use a Query.Builder
in the query()
method and on this you can set the rangeQuery
SearchResponse<Item> response = elasticsearchClient.search(q -> q
.index("itemindex")
.query(queryBuilder -> queryBuilder.range(rangeQuery))
), Item.class);