I create an index to store the duration of how long people watching a certain video, the index structure like this:
{
"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:
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:
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?