# Want to have counter field

**URL:** <https://discuss.elastic.co/t/want-to-have-counter-field/237077>\
**Category:** Kibana\
**Created:** [June 15, 2020, 6:55am UTC](https://discuss.elastic.co/t/want-to-have-counter-field/237077 "2020-06-15T06:55:45Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jyotis](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/jyotis/32/47985_2.png) [@jyotis](https://discuss.elastic.co/u/jyotis)\
**Post date:** [June 15, 2020, 6:55am UTC](https://discuss.elastic.co/t/want-to-have-counter-field/237077/1 "2020-06-15T06:55:46Z")

</div>

Hi Team,

I want to have a counter field which increases by 1 after each update.

Please advise a way to achieve it.

Thanks

---

<div class="post-metadata">

**Author:** ![wylie](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/wylie/32/81794_2.png) [@wylie](https://discuss.elastic.co/u/wylie)\
**Post date:** [June 15, 2020, 6:50pm UTC](https://discuss.elastic.co/t/want-to-have-counter-field/237077/2 "2020-06-15T18:50:42Z")

</div>

You can use a painless script to update the count:

```auto
    const response = await this._writeToCluster('update', {
      id: raw._id,
      index: this.getIndexForType(type),
      refresh,
      _source: true,
      body: {
        script: {
          source: `
              if (ctx._source[params.type][params.counterFieldName] == null) {
                ctx._source[params.type][params.counterFieldName] = params.count;
              }
              else {
                ctx._source[params.type][params.counterFieldName] += params.count;
              }
              ctx._source.updated_at = params.time;
            `,
          lang: 'painless',
          params: {
            count: 1,
            time,
            type,
            counterFieldName,
          },
        },
        upsert: raw._source,
      },
    });

```

---

<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 13, 2020, 6:50pm UTC](https://discuss.elastic.co/t/want-to-have-counter-field/237077/3 "2020-07-13T18:50:45Z")

</div>

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