Search code examples
elasticsearchelasticsearch-dsl

Elastic search create a dynamic field in response


I am working on a Elasticsearch project. I want to get an additional column in response when an index is queried. Say for example, if I have an index with two columns num1 and num2, when this index is queried it should respond with two column (num1 and num2) but also with additional column add_result (which is actually a addition of two columns). If I query it normally like below it would respond with just two columns

{
  query:{
    match_all : {}
  }
}

In my use case I have tried:

{
  "runtime_mappings": {
    "add_result": {
      "type": "double",
      "script": "emit(doc['file_count'].value + doc['follower_count'].value)"
    }
  },
  "query": {
    "match_all": {}
  }
}

Solution

  • Yes, there are 2 ways:

    1. Using runtime field

    This feature is available since Elasticsearch 7.12. Simply make a GET request to the _search endpoint with the request body like this:

    {
      "runtime_mappings": {
        "add_result": {
          "type": "double",
          "script": "emit(doc['num1'].value + doc['num2'].value)"
        }
      },
      "fields": ["add_result", "num*"],
      "query": {
        "match_all": {}
      }
    }
    

    You need to explicitly specify that you want to get your runtime fields back in the fields parameter.

    2. Using script_field

    The request looks like this:

    {
      "query": {
        "match_all": {}
      },
      "fields": ["num*"],
      "script_fields": {
        "add_result": {
          "script": {
            "lang": "painless",
            "source": "doc['num1'].value + doc['num2'].value"
          }
        }
      }
    }
    

    Note that you still need to have the fields parameter, but you don't need to include your script_field (add_result in this case) in the fields parameter.