0

I have this data stored in the Elasticsearch which is in this json format:

{
   "qna": [
      {
         "qid": "1",
         "question": [
            "How to use the tool"
         ],
         "answer": "Create and administer your questions Content Designer UI.",
         "votes": "0"
      },
      {
         "qid": "2",
         "question": [
            "How can I include attachements"
         ],
         "answer": "Add an image attachment to the item using the Content Designer.",
         "votes": "0"
      }
   ]
}

Now I have written this code where when a question string is passed I am able to fetch the answer from Elasticsearch:

from elasticsearch import Elasticsearch

def search_es(question,index_name):

    es = Elasticsearch([{'host': 'localhost', 'port': 9200}])

    data = {
        "query": {
            "function_score":{
                "query":{

                    "match": {
                        'question': question
                    }
                },
                "field_value_factor":{
                    "field":"votes",
                    "modifier":"log2p"
                }
            }
        }
    }
    response = es.search(index=str(index_name).lower(), body=data)
    for items in response['hits']['hits']:
        score = items['_score']
        answer = source['a']
        score_answer.append([score,answer])

    score_answer.sort(key=lambda x: int(x[0]), reverse=True)
    # SELECT ONE ANSWER - TOP SCORED ANSWER
    print(score_answer[0][1])
    # CODE TO INCREASE VOTE OF THE SELECTED ANSWER
    increase_vote(score_answer[0][1])

def increase_vote(answer):
    # IMPLEMENT CODE HERE

As you can see the search_es() extracts and selects the top scored answer field. Now what I want to do is implement a function that will update the votes field associated with the selected answer and increase it by 1. I looked around and found few posts related to partial update of documents like this but am unable to figure out a way on how to update the field as described in my scenario?

user2966197
  • 2,793
  • 10
  • 45
  • 77
  • I suggest you do this in ES via `script`. Refer: https://www.elastic.co/guide/en/elasticsearch/guide/current/partial-updates.html#_using_scripts_to_make_partial_updates – Praneeth Mar 22 '18 at 09:37
  • Please read about the update method in python elastic api http://elasticsearch-py.readthedocs.io/en/master/api.html?highlight=update#elasticsearch.Elasticsearch.update – Lupanoide Mar 22 '18 at 09:40

0 Answers0