Update in Elastic Search not working properly, It is inserting sometime,sometime updating it

Viewed 47

I am trying to update tag field in elastic search if tag is present increase the count field.I tried to use update() function but it was giving me error so i used index() function. My code for updating the field is.

## result structure [{'_id': ObjectId('60b9c65b3bb2f938e00c2078'),
#  'hashTags': ["wildlife","nature"]}]
for i in result:
    if len(i['hashTags'])>0:
        for ele in i['hashTags']:
            ele = ele.lower().strip() 
            count=0
            res = es.search(index="hashtags-python",body={"query":{"term":{"hashtag":ele}}})
            if len(res["hits"]["hits"])>0:
                
                count = res["hits"]["hits"][0]["_source"]["count"]
                _id = res["hits"]["hits"][0]["_id"] ## id generated by elasticsearch
                
                count +=1
               
                
                doc={"hashtag":ele,"count":count}
                es.index(index="hashtags-python",doc_type='post_hashtag',id=_id,body=doc)

                
            else:
                doc={"hashtag":ele,"count":1}
                es.index(index="hashtags-python",doc_type='post_hashtag',body=doc)

When i am doing search query:

es.search(index="hashtags-python",body={"query":{"match":{"hashtag":"wildlife"}}})

The result it is giving:

{'took': 3,
 'timed_out': False,
 '_shards': {'total': 1, 'successful': 1, 'skipped': 0, 'failed': 0},
 'hits': {'total': {'value': 3, 'relation': 'eq'},
  'max_score': 3.3424008,
  'hits': [{'_index': 'hashtags-python',
    '_type': 'post_hashtag',
    '_id': '-QVPvnoBOGGQhTZbz_Vh',
    '_score': 3.3424008,
    '_source': {'hashtag': 'wildlife',
     'count': 80,
     }},
   {'_index': 'hashtags-python',
    '_type': 'post_hashtag',
    '_id': 'LAVevnoBOGGQhTZbH_7v',
    '_score': 3.3424008,
    '_source': {'hashtag': 'wildlife',
     'count': 2
    }},
   {'_index': 'hashtags-python',
    '_type': 'post_hashtag',
    '_id': 'AgVPvnoBOGGQhTZb0_b2',
    '_score': 3.3424008,
    '_source': {'hashtag': 'wildlife',
     'count': 79,
     }}
           


 ]}}

What is wrong in this approach?

0 Answers
Related