ruby-on-railsrubyelasticsearchruby-on-rails-7ruby-3

Elasticsarch - How Do You Build A Search Query For An Object With Two Keys?


I have an Elasticsearch index with an array of items that looks like:

[{
  ...,
  "_source": {
    "id": ....
    "name": "apples",
    "organization_size": {
      "start": 0
      "end": 99 
    } 
  }    
}, {
  ...,
  "_source": {
    "id": ....
    "name": "bananas",
    "organization_size": {
      "start": 100
      "end": 499
    } 
  }    
}]

I am getting the following URL params from the front-end client:

filters[organization_size][][key][start]: 0
filters[organization_size][][key][end]: 99

What's the proper way of building out an Elasticsearch query string here so that the above request returns the "apples" result?

I am using Ruby on Rails, but the ES query buildout can be agnostic.


Solution

  • To build an Elasticsearch query that matches documents based on the provided organization size range from the front-end client, you have to ensure that your organization_size field is properly mapped in your index mapping. The start and end fields of the organization_field should be of an integer type.

    {
      "mappings": {
        "properties": {
          "organization_size": {
            "properties": {
              "start": { "type": "integer" },
              "end": { "type": "integer" }
            }
          }
        }
      }
    }
    

    And then you will be able to define a multi terms query to be able to return apples if the two matches.

    {
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "organization_size.start": 0
              }
            },
            {
              "term": {
                "organization_size.end": 99
              }
            }
          ]
        }
      }
    }
    

    Note that you can’t change the type of an existing field in the mapping. You would need to create a new index with the correct mapping and reindex your data if necessary.