16.6 C
Jaipur
Wednesday, December 1, 2021

Elasticsearch Range Query Tutorial

Must read

In Elasticsearch, we can get the results of documents that match a specific range using the range query.

Throughout this guide, you will learn to define a range parameter in your search query using Boolean expressions such as greater than, less than, and more.

Elasticsearch Range Query: Basic Usage

To specify a specific range in a search query, we can use the range parameter followed by the field and the conditions to check.

Take the query below that returns the documents where the field AvgTicketPrice is greater than 600 and less than 800

GET /kibana_sample_data_flights/_search
{
“query”: {
“range”: {
“AvgTicketPrice”: {
“gte”: 600,
“lte”: 800
  }
    }
  }
}

Below is the example return results:

Understanding the Query

In the example above, we set the range in the query. The range keyword requires the field parameter, which defines the field to search.

We then proceed to define the parameter for the field. These are Boolean conditions such as:

  1. gt – greater than
  2. gte – greater than or equal to
  3. lt – less than
  4. lte – less than or equal to

Querying a Time Range

If the field you wish to search is of type date, you can use the above conditionals followed by the date math defined in the resource below:

Elasticsearch Date math docs

Consider the following value that uses the time_zone parameter to convert the time to UTC value and searches for a range.

GET /kibana_sample_data_flights/_search
{
“query”: {
“range”: {
“timestamp”: {
“time_zone”: “+03:00”,
“gte”: “2021-10-14T05:22:14”,
“lte”: “now”
  }
    }
  }
}

The above query should return the documents where the timestamp is greater than 2021-10-14 at 05:22:14.

Here are example results:

NOTE: time_zone does not affect the now parameter.

Greater than

You do not have to combine the conditionals such as greater than and less than; you can use an individual range, as shown in the example below:

GET /kibana_sample_data_flights/_search
{
“query”: {
“range”: {
“DistanceMiles”: {
“gte”: 10000
  }
    }
  }
}

The example above returns the documents where the DistanceMiles is greater than 10000.

The response is below:

Boolean

To check for a range where the field type is a Boolean value, you can use lte or gte. For example, to get the documents for canceled flights, we can run a request as:

GET /kibana_sample_data_flights/_search
{
“query”: {
“range”: {
“Cancelled”: {
“gte”: true
  }
    }
  }
}

In the example above, we pass the range to check as a Boolean true.

The results are as shown:

Closing

In this guide, you learned how to use the range query in Elasticsearch to filter for results that match a specific range.

Source link

- Advertisement -

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisement -

Latest article