Elasticsearch Range Query

What it does

The Range Query in Elasticsearch is used to find documents where the field values are within a specified range. It can be used for various purposes, such as:

  • Finding products within a certain price range
  • Retrieving documents created between two dates
  • Filtering results based on alphabetical order of terms

Syntax

The basic syntax for a Range Query is:

{
  "range": {
    "field_name": {
      "gte": lower_bound,
      "lte": upper_bound
    }
  }
}

Where:

  • field_name: The field to query
  • gte: Greater than or equal to
  • lte: Less than or equal to

Other operators include:

  • gt: Greater than
  • lt: Less than

For more details, refer to the official Elasticsearch Range Query documentation.

Example Query

Here's an example Range Query to find products with prices between $50 and $100:

GET /products/_search
{
  "query": {
    "range": {
      "price": {
        "gte": 50,
        "lte": 100
      }
    }
  }
}

Common Issues

  1. Data type mismatch: Ensure the field type matches the range values you're querying.
  2. Date format issues: When querying date fields, make sure to use the correct date format.
  3. Performance on large datasets: Range queries can be slower on very large datasets, especially with high cardinality fields.

Best Practices

  1. Use the appropriate data type for your fields (e.g., date for dates, integer or float for numbers).
  2. For better performance on large datasets, consider using numeric range fields.
  3. When working with dates, use date math expressions for dynamic ranges.
  4. Combine range queries with other query types for more complex filtering.

Frequently Asked Questions

Q: Can I use Range Query for text fields?
A: Yes, you can use Range Query for text fields, but it's more commonly used for numeric and date fields. For text fields, it will use lexicographical order.

Q: How do I specify an unbounded range?
A: To specify an unbounded range, omit either the upper or lower bound. For example, use only "gt": 100 for values greater than 100.

Q: Can I use Range Query in a filter context?
A: Yes, Range Query can be used in both query and filter contexts. Using it in a filter context can improve performance as it doesn't calculate relevance scores.

Q: How does Range Query handle missing values?
A: By default, Range Query doesn't match documents where the field is missing. You can use the missing parameter to specify a value for missing fields.

Q: Is it possible to use Range Query with nested fields?
A: Yes, you can use Range Query with nested fields by combining it with a Nested Query. This allows you to apply the range conditions to fields within nested objects.

Pulse - Elasticsearch Operations Done Right

Stop googling errors and staring at dashboards.

Free Trial

Subscribe to the Pulse Newsletter

Get early access to new Pulse features, insightful blogs & exclusive events , webinars, and workshops.