# ウォッチャーにおいて計算結果をフィールドとして追加する方法

**URL:** <https://discuss.elastic.co/t/topic/188003>\
**Category:** 日本語による質問・議論はこちら\
**Tags:** elastic-stack-alerting\
**Created:** [June 28, 2019, 9:25am UTC](https://discuss.elastic.co/t/topic/188003 "2019-06-28T09:25:30Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![tsgkdt](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/tsgkdt/32/39151_2.png) [@tsgkdt](https://discuss.elastic.co/u/tsgkdt)\
**Post date:** [June 29, 2019, 12:52pm UTC](https://discuss.elastic.co/t/topic/188003/2 "2019-06-29T12:52:13Z")

</div>

こんにちわ。

以前Watcherの質問でありました内容に少し付け足せば可能かと思います。

> [@Watcher Index Actionで、ドキュメントを分けて出力する](https://discuss.elastic.co/t/watcher-index-action/181738):
>
> 基礎的な質問で恐縮ですが、WatcherのIndex Actionを利用すると、デフォルトでは、集計結果が、一つのドキュメントにまとめられて出力されます。 これを、Watcherで引っかかったドキュメントが、そのまま別々の状態で出力されるように設定をしたいです。 たとえば、 ①下記のような３つのデータを用意 \*doc1 pc\_name : A feature : B \*doc2 pc\_name : A feature : C \*doc3 pc\_name : B feature : B ②Watcherで、FeatureにBが含まれるときに、Indexを作成するように設定 ③doc1とdoc3が、一つのインデックスに、別々のドキュメントして出力 という流れをつくりたいです 初歩的なミスなのかもしれませんが、、下記の通り、Transform句を使用して作成してみたのですが、「no requests added」というエラーが出てしまいました。 { "trigger": { "schedule": { "inte…

transformでこのようにしております。  
`ctx.payload.hits.hits[i]['打率'] = ` の部分がフィールドを追加しているところになります。  
(蛇足ですが、ゼロ除算、ぬるぽなどは別途考慮ください)

```yml
"actions": {
    "index_payload": {
      "transform": {
        "script": """
        for (int i = 0; i < ctx.payload.hits.hits.length; ++i) {
          ctx.payload.hits.hits[i] = ctx.payload.hits.hits[i]._source;
          ctx.payload.hits.hits[i]['打率'] = (double)ctx.payload.hits.hits[i]['安打'] / (double)ctx.payload.hits.hits[i]['打数'];
        }
        return ['_doc' : ctx.payload.hits.hits];
        """
      },
      "index": {
        "index": "watcher-index"
      }
    }
  }

```

実際に登録されるindexはこのようになりました。

```auto
{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 2,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "watcher-index",
        "_type" : "_doc",
        "_id" : "XXFIo2sBsZpVTu8PuMgc",
        "_score" : 1.0,
        "_source" : {
          "安打" : 2,
          "打数" : 4,
          "打率" : 0.5
        }
      },
      {
        "_index" : "watcher-index",
        "_type" : "_doc",
        "_id" : "XnFIo2sBsZpVTu8PuMgc",
        "_score" : 1.0,
        "_source" : {
          "安打" : 1,
          "打数" : 5,
          "打率" : 0.2
        }
      }
    ]
  }
}

```

打率が計算されて追加されていることが確認できました。

ご参考になれば幸いです。

動作確認環境： Elasticseardch 7.2.0

---

_[View the full topic](https://discuss.elastic.co/t/topic/188003)._
