'Range queries in Elasticsearch Java API

I have two fields in my ES index: min_duration and max_duration. I want to create a query to find all the documents for input duration such that :

min_duration<=duration<=max_duration

For example if duration is 30 seconds then I should get all docs having min_duration less than eq to duration and duration less than eq to max_duration.

I am using ES Java API and seems like range filter is the way to go. I have constructed the range filter as follows:

val filter = FilterBuilders.andFilter( FilterBuilders.rangeFilter("min_duration").lte(duration),FilterBuilders.rangeFilter("max_duration").gte(duration))

Though it still not seems to work for me. Is it the correct way to build this type of query or am I missing something?

Thanks.



Solution 1:[1]

Try doing it with bool query. Wrap your two range clauses inside it like

QueryBuilder qb = boolQuery()
    .must(rangeQuery("max_duration").gte(duration))
    .must(rangeQuery("min_duration").lte(duration));

Does this help?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ChintanShah25