Search code examples
elasticsearchkibanaelasticsearch-painless

Elasticsearch - Create new field with script result as value


How do I create a new field called "message" which has the type "keyword" and the content of my script result:

GET log-sup-app1-32012-2021-11-08t11-00-49/_search
{
  "script_fields": {
    "message": {
      "script": { 
        "source": """
            String str = doc['@mt'].value;
            
            Map m = new HashMap();
            
            for (key in params._source.keySet()) {
              if (doc.containsKey(key)) {
                if (doc[key].size() != 0) {
                  m.put(key, doc[key].value.toString());
                }
              }
            }
            
            for (Map.Entry entry : m.entrySet()) {
              str = str.replace("{" + entry.getKey() + "}", entry.getValue());
            }
            
            return str; (e.g. returns 'This is the Test Result')
          """
      }
    }
  }
}

The expected property:

{
  "properties": {
    "message": {
      "type": "keyword"
    }
  }
}

The expected search result:

{
  "message" : "This is the Test Result"
}

Solution

  • Stack Management -> My Pattern -> Scripted Fields fixed the issue or using runtime fields