如何在ElasticSearch8.8.0中编写范围查询

9jyewag0  于 2023-10-17  发布在  ElasticSearch
关注(0)|答案(1)|浏览(128)

在我的Sping Boot 示例中,我在为运行在Docker上的ElasticSearch编写范围查询时遇到问题。
我试着写了RangeQuery,但在elasticsearchClient.search.中无法实现
我怎么能这么做呢?
下面是代码片段

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());
}

这就是问题所在

SearchResponse<Item> response = elasticsearchClient.search(q ->
                q.index("itemindex").query(rangeQuery), Item.class);

Cannot resolve method 'query(RangeQuery)'
ipakzgxi

ipakzgxi1#

您需要在query()方法中使用Query.Builder,在此可以设置rangeQuery

SearchResponse<Item> response = elasticsearchClient.search(q -> q
  .index("itemindex")
  .query(queryBuilder -> queryBuilder.range(rangeQuery))
  ), Item.class);

相关问题