Want to have counter field

Hi Team,

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

Please advise a way to achieve it.

Thanks

You can use a painless script to update the count:

    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,
      },
    });

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