07 May 2020

Kibana substring in scripted fields

Let say we have field datetime with type date in elasticsearch (eg: "2018-09-15T17:16:47") .
We want to get value 17 (hours),

We can achieve this by create Scripted field either  (1) in kibana scripted field, or (2)put it directly in your query.
Name it to sc-hour_myt.


(1) kibana scripted field.
String masa = String.valueOf(doc['datetime'].value); 

// since my timezone is +0800
int hour = Integer.parseInt(masa.substring(11,13)) + 8 ; 
if (hour >= 24) {
hour = hour - 24;  
}

String minute = masa.substring(14,16);
String second = masa.substring(17,19);

String utc = String.valueOf(hour) + minute + second;
return hour;


(2) put directly in your query:
{
  "query": {
    "match_all": {}
  },
  "_source": ["datetime"],
  "script_fields": {
    "sc-hour_myt": {
      "script": {
        "lang": "painless",
        "source": """
              String masa = String.valueOf(doc['datetime'].value);
              int hour = Integer.parseInt(masa.substring(11,13)) + 8 ;
              if (hour >= 24) {
              hour = hour - 24; 
              }
              String minute = masa.substring(14,16);
              String second = masa.substring(17,19);
             
              String utc = String.valueOf(hour) + minute + second;
              return hour;
        """
      }
    }
  }
}


--------------------------------------------------------------

This will result:
{ "_id": "CqSU6nEBOMr994UREJt1", "datetime": "2018-09-15T07:16:47", "sc-hour_myt": [ 15 ] }, { "_id": "C6SU6nEBOMr994UREJt1", "datetime": "2018-09-15T07:16:47", "sc-hour_myt": [ 15 ] },

No comments:

Post a Comment

Terima kasih