# Execute scripted field on latest document instead of oldest?

**URL:** <https://discuss.elastic.co/t/execute-scripted-field-on-latest-document-instead-of-oldest/197245>\
**Category:** Kibana\
**Created:** [August 29, 2019, 12:59am UTC](https://discuss.elastic.co/t/execute-scripted-field-on-latest-document-instead-of-oldest/197245 "2019-08-29T00:59:06Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Sjaak01](https://avatars.discourse-cdn.com/v4/letter/s/73ab20/32.png) [@Sjaak01](https://discuss.elastic.co/u/Sjaak01)\
**Post date:** [August 29, 2019, 12:59am UTC](https://discuss.elastic.co/t/execute-scripted-field-on-latest-document-instead-of-oldest/197245/1 "2019-08-29T00:59:06Z")

</div>

Hi,

I have this scripted field that calculates the delay of incoming data. I'm made a table viz with unique count on the name field, the split it with a terms bucket for the name and a term for the delay below that. The goal is to show the latest document per name.

The problem I'm having is that the scripted field appears to be returning the calculation for the oldest field, but I want it executed on the newest field.

My data looks something like this

```
name: John
@original_ingest_time: 18:05

name: John
@original_ingest_time: 18:05

name: John
@original_ingest_time: 18:00

```

I tried many sorting options but its always returning results for the oldest document.

```
if (new Date().getTime() - doc['@original_ingest_time'].value.getMillis() >= 86400000) {
    return "High"
} else if (new Date().getTime() - doc['@original_ingest_time'].value.getMillis() >= 648000000) {
    return "Medium"
} else if (new Date().getTime() - doc['@original_ingest_time'].value.getMillis() >= 3600000) {
    return "Low"
} else if (new Date().getTime() - doc['@original_ingest_time'].value.getMillis() >= 0) {
    return "Normal"
}
```

---

<div class="post-metadata">

**Author:** ![mikecote](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/mikecote/32/58549_2.png) [@mikecote](https://discuss.elastic.co/u/mikecote)\
**Post date:** [August 30, 2019, 3:07pm UTC](https://discuss.elastic.co/t/execute-scripted-field-on-latest-document-instead-of-oldest/197245/2 "2019-08-30T15:07:35Z")

</div>

Hi @Sjaak01,

Can you provide more details or a screen grab about the Metrics and Buckets you have created for your data table visualization? (dropdown values, etc) It does sound like a sorting problem somewhere.

Mike.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [September 27, 2019, 3:07pm UTC](https://discuss.elastic.co/t/execute-scripted-field-on-latest-document-instead-of-oldest/197245/3 "2019-09-27T15:07:36Z")

</div>

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