# Watcherで割合をしきい値にしたり、出力したりする方法

**URL:** <https://discuss.elastic.co/t/watcher/233636>\
**Category:** 日本語による質問・議論はこちら\
**Created:** [May 21, 2020, 12:41am UTC](https://discuss.elastic.co/t/watcher/233636 "2020-05-21T00:41:59Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![hashimoto](https://avatars.discourse-cdn.com/v4/letter/h/d9b06d/32.png) [@hashimoto](https://discuss.elastic.co/u/hashimoto)\
**Post date:** [May 21, 2020, 12:41am UTC](https://discuss.elastic.co/t/watcher/233636/1 "2020-05-21T00:41:59Z")

</div>

現在nginxのアクセスログを蓄積しており過去n分間の取引のうち処理時間(duration.rpが当たります)m秒以上がx%以上だったら警告というような運用を考えています。

データとして以下のようにn秒以上の件数をすべて抜き出し0秒以上の全件で割れば算出できるのではと考えましたがctx.payload.aggregations.duration\_sla.bucketsの個別の要素へのアクセス方法と計算処理をどこに書けばよいかがいまいちわかっておらず、教えていただきたいです。

bucketsについては右記のようなアクセスを試して失敗しています。ctx.payload.aggregations.duration\_sla.buckets['0.0-\*']

```auto
{
  "trigger": {
    "schedule": {
      "interval": "1m"
    }
  },
  "input": {
    "search": {
      "request": {
        "search_type": "query_then_fetch",
        "indices": [ 
          <<index>>
         ],
        "types": [],
        "body": {
          "query": {
            "bool": {
              "must": [
                {
                  "match_all": {}
                },
                {
                  "range": {
                    "timestamp.timefilter": {
                      "gte": "now-{{ctx.metadata.time_window}}"
                    }
                  }
                }
              ],
              "filter": [],
              "should": [],
              "must_not": []
            }
          },
          "aggs": {
            "duration_sla": {
              "range": {
                "field": "duration.rp",
                "ranges": [
                  {
                    "from": 0
                  },
                  {
                    "from": 3
                  },
                  {
                    "from": 5
                  }
                ]
              }
            }
          }
        }
      }
    }
  },
  "transform": {
    ここで割合を算出？
  },
  "condition": {
    ここで割合のしきい値超過を判定
  },
  "actions": {
    "email_me": {
      "email": {
        "profile": "standard",
        "attachments": {
          "<<filename>>": {
            "reporting": {
              "url": "<<URL>>",
              "retries": 6,
              "interval": "20s",
              "auth": {
                "basic": {
                  "username": "<<id>>",
                  "password": "<<pass>>"
                }
              }
            }
          }
        },
        "from": "<<mail>>",
        "to": [
          "<<mail>>"
        ],
        "cc": [],
        "subject": "<<subject>>",
        "body": {
          "html": "{{#ctx.payload.aggregations.duration_sla.buckets}}{{key}}:({{doc_count}}):{{/ctx.payload.aggregations.duration_sla.buckets}}"
        }
      }
    }
  },
  "metadata": {
    "time_window": "2m"
  }
}

```

---

<div class="post-metadata">

**Author:** ![Koji\_Kawamura](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/koji_kawamura/32/93938_2.png) [@Koji\_Kawamura](https://discuss.elastic.co/u/Koji_Kawamura)\
**Post date:** [May 21, 2020, 6:12am UTC](https://discuss.elastic.co/t/watcher/233636/2 "2020-05-21T06:12:07Z")

</div>

@hashimoto さん、

- トップレベルの`transform`は`condition`の評価が終わった後、`action`へ引き渡す際の変換です。
- `search`の出力を変換するには`chain`インプットを使う必要があります。
- `chain`インプットの結果にアクセスするには各インプットの名前が必要です。`ctx.payload.first.aggregations`など。

こちら、試しに作ってみたのでご参考までに。

サンプルデータ:

```auto
POST forum_233636/_bulk
{"index": {}}
{"@timestamp": "2020-05-21T13:55:01+09:00", "duration.rp": 1}
{"index": {}}
{"@timestamp": "2020-05-21T13:55:02+09:00", "duration.rp": 1}
{"index": {}}
{"@timestamp": "2020-05-21T13:55:03+09:00", "duration.rp": 3}
{"index": {}}
{"@timestamp": "2020-05-21T13:55:04+09:00", "duration.rp": 4}
{"index": {}}
{"@timestamp": "2020-05-21T13:55:05+09:00", "duration.rp": 5}
{"index": {}}
{"@timestamp": "2020-05-21T13:55:06+09:00", "duration.rp": 7}
{"index": {}}
{"@timestamp": "2020-05-21T13:55:07+09:00", "duration.rp": 11}
{"index": {}}
{"@timestamp": "2020-05-21T13:55:08+09:00", "duration.rp": 1}
{"index": {}}
{"@timestamp": "2020-05-21T13:55:09+09:00", "duration.rp": 1}
{"index": {}}
{"@timestamp": "2020-05-21T13:55:10+09:00", "duration.rp": 1}

```

Watcher定義:

```auto
{
  "trigger": {
    "schedule": {
      "interval": "30m"
    }
  },
  "input": {
    "chain": {
      "inputs": [
        {
          "first": {
            "search": {
              "request": {
                "search_type": "query_then_fetch",
                "indices": [
                  "forum_233636"
                ],
                "body": {
                  "size": 0,
                  "query": {
                    "match_all": {}
                  },
                  "aggs": {
                    "duration_sla": {
                      "range": {
                        "field": "duration.rp",
                        "ranges": [
                          {
                            "from": 0
                          },
                          {
                            "from": 3
                          },
                          {
                            "from": 5
                          }
                        ]
                      }
                    }
                  }
                }
              }
            }
          }
        },
        {
          "counts": {
            "transform": {
              "script": """
         return ['all': ctx.payload.first.aggregations.duration_sla.buckets[0].doc_count,
         'gte3ms': ctx.payload.first.aggregations.duration_sla.buckets[1].doc_count,
         'gte5ms': ctx.payload.first.aggregations.duration_sla.buckets[2].doc_count]
      """
            }
          }
        }
      ]
    }
  },
  "condition": {
    "script": {
      "source": """
        return true || ((float) ctx.payload.counts.gte3ms / ctx.payload.counts.all) > 0.5
                || ((float) ctx.payload.counts.gte5ms / ctx.payload.counts.all) > 0.2;
        """
    }
  },
  "actions": {
    "my-logging-action": {
      "logging": {
        "level": "info",
        "text": "{{ctx.payload.counts}}"
      }
    }
  }
}

```

---

<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 18, 2020, 6:12am UTC](https://discuss.elastic.co/t/watcher/233636/3 "2020-06-18T06:12:17Z")

</div>

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