Dibish
Dibish

Reputation: 9293

How to set counter field in elasticsearch

I need to increment the field 'post_count' with +1 in elasticsearch For ex: In my case When I click a button the post_count need to increment

   "hits": {
      "total": 1,
      "max_score": 1,
      "hits": [
         {
            "_index": "test_work",
            "_type": "user",
            "_id": "d989dd8629f8b6cc59faf8a1aa2328c8",
            "_score": 1,
            "_source": {
               "first_name": "test",
               "last_name": "amt",
               "post_count":0
            }
         }
      ]

Is there any single query to increment post_count in each update

Upvotes: 0

Views: 2776

Answers (2)

Davidacce
Davidacce

Reputation: 235

You can also control the increment of the counter using a parameter in your script. If you are using ES 1.3+ you might get an error saying "dynamic scripting disabled", in order to avoid it you need to specify the script language, in this case groovy.

POST /test_work/user/d989dd8629f8b6cc59faf8a1aa2328c8/_update
{
    "script" : "ctx._source.post_count+=increment",
    "params" : {
        "increment" : 4
    },"lang":"groovy"
}

Upvotes: 2

Andrei Stefan
Andrei Stefan

Reputation: 52368

Try something like this:

POST /test_work/user/d989dd8629f8b6cc59faf8a1aa2328c8/_update
{
   "script" : "ctx._source.post_count+=1"
}

Upvotes: 4

Related Questions