# Copy fields from latest doc in Transforms

**URL:** <https://discuss.elastic.co/t/copy-fields-from-latest-doc-in-transforms/231784>\
**Category:** Elasticsearch\
**Created:** [May 8, 2020, 7:04pm UTC](https://discuss.elastic.co/t/copy-fields-from-latest-doc-in-transforms/231784 "2020-05-08T19:04:36Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![xbeumala](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/xbeumala/32/67986_2.png) [@xbeumala](https://discuss.elastic.co/u/xbeumala)\
**Post date:** [May 8, 2020, 7:04pm UTC](https://discuss.elastic.co/t/copy-fields-from-latest-doc-in-transforms/231784/1 "2020-05-08T19:04:37Z")

</div>

Hi all,

I have an analytics system and for every user action I log an event. The event contains event specific but also session level data.

I've created a transform to create a user centric entity. on the transform I want to copy several values from the latest event document to the transform document.

I've got it working with the latestDocument example:

```auto
    "latest_doc": {
        "scripted_metric": {
          "init_script": "state.timestamp_latest = 0L; state.last_doc = ''", 
          "map_script": """ 
            def current_date = doc['ts'].getValue().toInstant().toEpochMilli();
            if (current_date > state.timestamp_latest)
            {state.timestamp_latest = current_date;
            state.last_doc = new HashMap(params['_source']);}
          """,
          "combine_script": "return state", 
          "reduce_script": """ 
            def last_doc = '';
            def timestamp_latest = 0L;
            for (s in states) {if (s.timestamp_latest > (timestamp_latest))
            {timestamp_latest = s.timestamp_latest; last_doc = s.last_doc;}}
            return last_doc
          """
        }
      }

```

What I'd like is a way to just copy some of the fields directly on the root without duplicating the scripted metric. What would be a good way to achieve it?

many thanks in advance

---

<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:** [June 5, 2020, 7:04pm UTC](https://discuss.elastic.co/t/copy-fields-from-latest-doc-in-transforms/231784/2 "2020-06-05T19:04:37Z")

</div>

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