# Machine Learning on scripted field?

**URL:** <https://discuss.elastic.co/t/machine-learning-on-scripted-field/89054>\
**Category:** Elasticsearch\
**Tags:** elastic-stack-machine-learning\
**Created:** [June 12, 2017, 1:56pm UTC](https://discuss.elastic.co/t/machine-learning-on-scripted-field/89054 "2017-06-12T13:56:26Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![richcollier](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/richcollier/32/115035_2.png) [@richcollier](https://discuss.elastic.co/u/richcollier)\
**Post date:** [June 12, 2017, 3:52pm UTC](https://discuss.elastic.co/t/machine-learning-on-scripted-field/89054/2 "2017-06-12T15:52:41Z")

</div>

Hello,

Yes, creating a scripted\_field must be part of the datafeed configuration ([https://www.elastic.co/guide/en/x-pack/5.4/ml-put-datafeed.html](https://www.elastic.co/guide/en/x-pack/5.4/ml-put-datafeed.html)).

To accomplish:

1. Create an advanced job (only can do this technique on advanced jobs)
2. Configure the job as you normally would. When creating detectors, instead of choosing an existing field, choose a name that we'll later assign to the script field. In this example, we are choosing the field name total\_error\_count which doesn't exist in our documents
3. Once your job is configured as you like, go to the "Edit JSON" tab
4. Append a new script\_fields parameter inside the datafeed\_config object. The syntax for script\_fields is identical to that used by Elasticsearch. You can find [more information on the syntax here](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-script-fields.html). We'll add our total\_error\_count script field to the script\_fields object. The script will do a simple addition of two fields in the document to produce a "total" error count:

```auto
  "datafeed_config": {
    "query": {
      "match_all": {}
    },
    "query_delay": "60s",
    "frequency": "150s",
    "scroll_size": 1000,
    "indexes": [
      "rally-2017"
    ],
    "types": [
      "metrics"
    ],
    "script_fields": {
      "total_error_count": {
        "script": {
          "lang": "painless",
          "inline": "doc['error_count'].value + doc['aborted_count'].value"
        }
      }
    }
  }

```

When done editing the JSON, you can verify the output of your script with the results with the "Data Preview" tab. When satisfied, press Save.

You'll notice that our detector referenced "total\_error\_count", which is generated at runtime by the script. Every time a document is loaded by Elasticsearch, the script is evaluated and its result outputted as a "virtual" field. This is then used by the ML job.

---

_[View the full topic](https://discuss.elastic.co/t/machine-learning-on-scripted-field/89054)._
