OpenSearch is a text-based search engine based on lucene in which we can store and query data effectively.
It provides a Java SDK client that helps to access OpenSearch through Java application.
Range query allows us to query indices with a field whose value lies within a given range.
OpenSearch Java SDK provides RangeQuery builder that we can use.
RangeQuery rangeQuery = new RangeQuery.Builder().field("age").from(JsonData.of("15")).to(JsonData.of("22")).build(); SearchResponsesearchResponse = openSearchClient.search(s -> { s.index("index-name"); s.query(rangeQuery._toQuery()); return s; }, Index.class); for (int i = 0; i < searchResponse.hits().hits().size(); i++) { System.out.println(searchResponse.hits().hits().get(i).source()); }
The above Range Query will search for age
between 15
and 22
.
We can also query between multiple fields in the specified range. The below query will search for age
greater than and equal to 20
and salary
less than and equal to 34000
RangeQuery rangeQuery = new RangeQuery.Builder().field("age").gte(JsonData.of("20")).field("salary").lte(JsonData.of("34000")).build(); SearchResponsesearchResponse = openSearchClient.search(s -> { s.index("index-name"); s.query(rangeQuery._toQuery()); return s; }, Index.class); for (int i = 0; i < searchResponse.hits().hits().size(); i++) { System.out.println(searchResponse.hits().hits().get(i).source()); }
The available options for range query is
- from
- to
- gte: greater than equal to
- gt: greater than
- lte: less than equal to
- lt: less than