Add a custom field in Kibana

Hi,

I wanted to add a field where it calculates the age of a person, thus --> Birth date - Now

I tried to implement this guide. [see the Datetime Now Example].

  1. Somehow I got an error said cannot resolve symbol [zdt].

Screenshot 2022-12-29 at 08.19.59

Then, I suspect that zdt is the brief term for ZonedDateTime. I changed the zdt to ZonedDateTime, then I got an error said static method [java.time.ZonedDateTime, toInstant/0] not found. Idk what's wrong here?
Screenshot 2022-12-29 at 08.19.21

  1. Do we need to define the parameter "now" as in the Input? Where do we do that? How?

Please kindly advise. Thanks!

In your first try you it was complaining because in line 2 you named the variable lastScraped then used zdt in line 3.

Check the code below, you can run it on the Kibana Dev tools and later move the source of the script to your data view.

# Create a testing index
PUT discuss-322138
{
  "settings": {
    "number_of_replicas": 1
  }, 
  "mappings": {
    "properties": {
      "name": { "type": "text" },
      "birthDate": { "type": "date"}
    }
  }
}

# Add some data
POST discuss-322138/_bulk
{ "index": {}}
{ "name": "john", "birthDate": "1965-12-29"}
{ "index": {}}
{ "name": "mary", "birthDate": "1985-12-29"}

# Search with a runtime field
GET discuss-322138/_search
{
  "fields": [
    "age"
  ], 
  "runtime_mappings": {
    "age": {
      "type": "long",
      "script": {
        "source": """
        Instant now = Instant.ofEpochMilli(new Date().getTime());
        ZonedDateTime zdtNow = ZonedDateTime.ofInstant(now, ZoneId.of('Z'));
        ZonedDateTime zdtBirth = doc['birthDate'].value;
        
        emit(ChronoUnit.YEARS.between(zdtBirth, zdtNow))
        """
      }
    }
  }
}

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.