Last Valid Value of a Field in Scripted Fields

You can check this discuss post, this is about merging 2 documents. Conceptually you want the same but in addition you want to apply a calculation. In a nutshell you need to get the values for x and y in the map phase and do the calculation in the reduce phase.

If you haven't worked with aggregations before: https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html

If you want to create new documents, checkout transform: https://www.elastic.co/guide/en/elasticsearch/reference/current/transforms.html

I know this is a lot to read. It might be easier to look for blogs first, e.g. https://www.elastic.co/blog/intro-to-aggregations/ or this webinar recording about transform: https://www.elastic.co/webinars/introducing-data-frame-transforms-for-elastic-machine-learning