简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM