# Python Elasticsearch Bulk Conditional Upsert

**URL:** https://discuss.elastic.co/t/python-elasticsearch-bulk-conditional-upsert/71573
**Category:** Elasticsearch
**Created:** [January 13, 2017, 9:26pm UTC](https://discuss.elastic.co/t/python-elasticsearch-bulk-conditional-upsert/71573 "2017-01-13T21:26:07Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![nickvido](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/nickvido/32/13750_2.png) [@nickvido](https://discuss.elastic.co/u/nickvido)
#### Post date: [January 13, 2017, 9:26pm UTC](https://discuss.elastic.co/t/python-elasticsearch-bulk-conditional-upsert/71573/1 "2017-01-13T21:26:07Z")

</div>

Using elasticsearch-py python helpers library for bulk conditional scripted update:

```
from elasticsearch import Elasticsearch
from elasticsearch import helpers
es = Elasticsearch(host=YOUR_HOST)
actions = []

document = {
    "field1": "test_script_value1",
    "date": "2017-01-13T16:24:00Z"
}
action = {
    "_op_type": "update",
    "_index": "YOUR_INDEX_NAME",
    "_type": "YOUR_DOCUMENT_TYPE",
    "_id": YOUR_DOCUMENT_ID,
    "_source": {
        "script": {
            "inline": "if ((ctx._source.doc) && (ctx._source.doc.date > doc.date)) { ctx.op='noop' } else { ctx._source.doc=doc }",
            "params": { "doc": document }
        },
        "upsert": { "doc": document }
    }
}
actions.append(action)
helpers.bulk(es, actions)

```

Also this requires enabling scripting (be careful, this is not safe if your users can access the elastic instance) in elasticsearch.yml configuration file:

```
script.engine.groovy.inline.update: on 

```

Had a hard time finding the right documentation for this, so sharing in case it helps someone else (or me in the future).

Keywords: python, elastic, bulk, helpers, update, upsert, doc\_as\_upsert, script, conditional, date

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)
#### Post date: [February 10, 2017, 9:26pm UTC](https://discuss.elastic.co/t/python-elasticsearch-bulk-conditional-upsert/71573/2 "2017-02-10T21:26:44Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
