Search code examples
elasticsearchkibanaelasticsearch-painless

Runtime Field Script emit null value for long


I have a runtime field that converts a long field in milliseconds to seconds. The problem is sometimes there is no value present in that row for the field. To handle this, I added a check:

PUT /my-logs-dev/_mapping

{
    "runtime": {
      "fields.Metric.ElapsedSeconds": {
        "type": "long",
        "script": {
          "source": "if(doc['fields.Metric.ElapsedMilliseconds'].length>0) 
                         emit(Math.round(doc['fields.Metric.ElapsedMilliseconds'].value / 1000d)); 
                     else
                         emit(0);"
        }
      }
    }
}

This works, but I would much prefer to emit "no value" to match the input. This way, when we aggregate in, say, dashboards, they row is simply ignored rather then diluting the aggregate value with zeros. Appreciate any help!


Solution

  • Since emit() doesn't support emitting null, you can simply remove the else section and nothing will be emitter if the field is missing

    PUT /my-logs-dev/_mapping
    {
        "runtime": {
          "fields.Metric.ElapsedSeconds": {
            "type": "long",
            "script": {
              "source": """if(doc['fields.Metric.ElapsedMilliseconds'].length>0) 
                             emit(Math.round(doc['fields.Metric.ElapsedMilliseconds'].value / 1000d));"""
            }
          }
        }
    }