0
votes

User monthly salary range could be between the following ranges

1k - 2k USD
2k - 3k USD
3k - 4k USD
4k - 5k USD

the exact salary is not stored, but the salary range for an user should be stored. this should enable finding documents whose salary range falls between 2k - 5k USD. how should this be modeled in the index for search using the range query

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-range-query.html

1

1 Answers

1
votes

You can use range field types that represent a continuous range of values between an upper and lower bound and then query on the data using range query.

Adding a working example with index data, mapping, search query, and search result

Index Mapping:

{
  "mappings": {
    "properties": {
      "salary": {
        "type": "integer_range"
      }
    }
  }
}

Index Data:

{
  "salary" : { 
    "gte" : 1,
    "lt" : 2
  }
}
{
  "salary" : { 
    "gte" : 2,
    "lt" : 3
  }
}
{
  "salary" : { 
    "gte" : 3,
    "lt" : 4
  }
}
{
  "salary" : { 
    "gte" : 4,
    "lt" : 5
  }
}

Search Query:

{
  "query": {
    "range": {
      "salary": {
        "gte": 2,
        "lte": 5
      }
    }
  }
}

Search Result:

"hits": [
      {
        "_index": "64578350",
        "_type": "_doc",
        "_id": "2",
        "_score": 1.0,
        "_source": {
          "salary": {
            "gte": 2,
            "lt": 3
          }
        }
      },
      {
        "_index": "64578350",
        "_type": "_doc",
        "_id": "3",
        "_score": 1.0,
        "_source": {
          "salary": {
            "gte": 3,
            "lt": 4
          }
        }
      },
      {
        "_index": "64578350",
        "_type": "_doc",
        "_id": "4",
        "_score": 1.0,
        "_source": {
          "salary": {
            "gte": 4,
            "lt": 5
          }
        }
      }
    ]