Search code examples
pythonelasticsearchmappings

Use Python API to conditionally update ElasticSearch document


I am trying to update a document (by appending elements to a list), or create if it does not exists. For example, I want the document with id == Donald_Duck to add the elements of the list suggestions, if not present already.

name = 'Donald_Duck'
suggestions = ['Donald', 'Donald duck', 'Duck', 'Duck Avanger']
body = {
           "script" : "ctx._source.text += new_suggetions",
           "params" : { "new_suggestions" : suggestions},
            "upsert" : suggestions
        }


es.update(index=INDEX_NAME, doc_type='test', id=name, body=body)

Unfortunately I get a RequestError:

RequestError: TransportError(400, 'mapper_parsing_exception', 'failed to parse')  

This is how my mappings looks like:

mappings = {
  "mappings": {
    "test": { 
      "properties": { 
        "text":    { 
                    "type": "completion", 
                    "analyzer" : "simple",
                    "search_analyzer" : "simple" 
        }, 
      }
    }
  }
}

How can I fix this? If I have multiple documents, can I use the same code with the bulk API?


Solution

  • You have some typo in your body:

    body = {
        "script": "ctx._source.text += new_suggestions",
        "params": { "new_suggestions" : suggestions},
        "upsert": {
            "text": suggestions
        }
    }
    

    Plus, are you sure you have enabled the scripting for updates. Please read https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-scripting.html