# ElasticSearch upsert document with complex script

**URL:** https://discuss.elastic.co/t/elasticsearch-upsert-document-with-complex-script/176187
**Category:** Elasticsearch
**Created:** [April 10, 2019, 9:37am UTC](https://discuss.elastic.co/t/elasticsearch-upsert-document-with-complex-script/176187 "2019-04-10T09:37:44Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![tour\_young](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/tour_young/32/43841_2.png) [@tour\_young](https://discuss.elastic.co/u/tour_young)
#### Post date: [April 10, 2019, 9:37am UTC](https://discuss.elastic.co/t/elasticsearch-upsert-document-with-complex-script/176187/1 "2019-04-10T09:37:44Z")

</div>

I create an index to store the duration of how long people watching a certain video, the index structure like this:

```auto
{
    "first_watch_time": "2019-04-01T02:17:14.004Z",
    "last_watch_time": "2019-04-01T02:18:24.004Z",
    "duration": 70
}

```

when I create document I use the user\_id as the document \_id. For example when Bob(user\_id is 1) first watch the video, trigger an event, there is no document in the index, and so I create one for him:

```auto
PUT video_duration/video_duration/1
{
    "first_watch_time": event_time,
    "duration": 0
}

```

the field "first\_watch\_time" is when the event occurred. After a while when Bob click the pause button, trigger a new event, now I want to use the upsert syntax to update the duration:

```auto
POST video_duration/video_duration/1/_update
{
  "script": {
    "source": "ctx._source.duration += params.duration; ctx._source.last_watch_time = event_time",
    "lang": "painless",
    "params": {
      "duration": "duration(event_time - ctx._source['first_watch_time'])"
    }
  },
  "upsert": {
    "duration": 0,
    "first_watch_time": event_time
  }
}

```

now the question is I dont know how to write the params, and I find the value of the key in params seems to be a specific value number or string, and also I dont know how to subtract the two timestamp in script. Is this possible to use upsert to calculate the duration, or I have to first query the document, and the calculate the duration in memory and then use one more request to update it?

---

<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: [May 8, 2019, 9:37am UTC](https://discuss.elastic.co/t/elasticsearch-upsert-document-with-complex-script/176187/2 "2019-05-08T09:37:52Z")

</div>

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