# Aggregation to count consecutive instances of a given field value?

**URL:** <https://discuss.elastic.co/t/aggregation-to-count-consecutive-instances-of-a-given-field-value/276982>\
**Category:** Elasticsearch\
**Created:** [June 24, 2021, 9:08pm UTC](https://discuss.elastic.co/t/aggregation-to-count-consecutive-instances-of-a-given-field-value/276982 "2021-06-24T21:08:00Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![gpaciga](https://avatars.discourse-cdn.com/v4/letter/g/ac8455/32.png) [@gpaciga](https://discuss.elastic.co/u/gpaciga)\
**Post date:** [June 24, 2021, 9:08pm UTC](https://discuss.elastic.co/t/aggregation-to-count-consecutive-instances-of-a-given-field-value/276982/1 "2021-06-24T21:08:00Z")

</div>

I have an index that has a series of events:

```auto
[{
    @timestamp: "...",
    jobId: "123",
    result: "failure",
},{
    @timestamp: "...",
    jobId: "567",
    result: "success",
},{
   @timestamp: "...",
   jobId: "123",
   result: "failure"
}]

```

I would like to be able to set up alerting based on conditions like, "the same job has failed 3 times in a row". I believe I could do this as long as I have a query that can tell me, for each unique value of some field (`jobId` in this example), how many times in a row another field (`result`) has a particular value (`failure`). If the most recent result was `success`, the count would be 0.

One simple (but clunky) approach would be just to query all the logs, sorted by `@timestamp`, and calculate it myself, but I wonder if it is possible to do by aggregation instead. I thought of using a scripted field but I don't if it's possible to tabulate only recent and consecutive docs across shards.

Any ideas whether this is possible and what techniques to look into to do it?

---

<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:** [July 22, 2021, 9:08pm UTC](https://discuss.elastic.co/t/aggregation-to-count-consecutive-instances-of-a-given-field-value/276982/2 "2021-07-22T21:08:03Z")

</div>

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