0

I want to create a (url,visits) index on elasticsearch which will hold the number of visits a particular url every time I call function myfunction. How can I do that? So far, I have managed to create the insertion but I am unable to increase the counter.

def myfunction():
    a = elasticsearch.index(index='test_index_1' , doc_type='test_doc_type' , id="url" , body={'data' : {'visits' : 1} , 'doc_as_upsert' : True})
    app.logger.info(a)
    b = elasticsearch.update(index='test_index_1' , doc_type='test_doc_type' , id="url" , body={
        'script' : 'ctx._source.data.visits += visit',
        'params' : {
            'visit' : 1
        }
    })
    app.logger.info(b)
user706838
  • 5,132
  • 14
  • 54
  • 78
  • 1
    There is a proprty called `version` which is maintained for every document.It gets updated for every updation. You can use that. – Richa Mar 13 '16 at 05:48

1 Answers1

0

You should use the upsert parameter. The document with id:url should be created with a default visits:1 if it doesn’t already exist:

POST /test_index_1/test_doc_type/{id}/_update
{
   "script" : "ctx._source.visits+=1",
   "upsert": {
       "visits": 1
   }
}
Rahul
  • 15,979
  • 4
  • 42
  • 63
  • Thanks for your answer but how can I translate this to `elasticsearch-py`? this doesn't look like to work: `b = elasticsearch.update(index='test_index_1' , doc_type='test_doc_type' , id="url" , body={ 'script' : 'ctx._source.data.visits+=1', 'upsert' : { "visits": 1 } })` – user706838 Mar 13 '16 at 10:46
  • I haven't used elasticsearch-py but can you share the issue you are facing in converting this to elasticsearch-py syntax? – Rahul Mar 13 '16 at 15:19