21

I'm using Elasticsearch python client as http://elasticsearch-py.readthedocs.org/ I tried hard but still could not find the update api with upsert. Could anyone give me an example with ES python client upsert api please.

Jack
  • 5,540
  • 13
  • 65
  • 113

2 Answers2

32

The example code is following.

from elasticsearch import Elasticsearch
es = Elasticsearch("localhost:9200")
es.update(
    index="test",
    doc_type="test1",
    id="1",
    body={
        "doc": {"username": "Tom"}, 
        "doc_as_upsert": True
    }
)

If body is without doc_as_upsert=true the code would throw an exception when the id is not existing. Additionally, make sure your data were wrapped in doc.

Jaroslav Bezděk
  • 6,967
  • 6
  • 29
  • 46
  • 4
    > Additionally, please make sure your data were wrapped in doc{}. Thank you – Lelouch Lamperouge Jan 12 '16 at 00:56
  • 1
    @LelouchLamperouge is it compulsary to use `doc`? – anekix May 18 '17 at 07:37
  • How to upsert based on a condition? – user1870400 Jun 28 '18 at 08:11
  • So for passing body wrapped in doc, is there a way you can pass it json? It seems it has to be a dict so have to parse json to dict first, but I already have json and wanted to skip a step. I know I can do it using `requests` library and parsing the whole request as json myself. Too bad its not flexible like `helpers.bulk` which takes either. I suppose I could also use bulk and insert 1. – radtek May 19 '20 at 07:57
5

Method index(*args, **kwargs) adds or updates a typed JSON document in a specific index, making it searchable.

As pointed out in Python Elasticsearch Client -> API Documentation.

Nameless One
  • 1,615
  • 2
  • 23
  • 39
no_igor
  • 95
  • 1
  • 3
  • worked for me. not sure what's the difference between this solution and the accepted one (es.update). both worked well for me. – Hossein Kalbasi May 11 '21 at 14:56
  • index rewrites the entire document. For example if you had `{"key": "value"}` and then you use index on the same doc id with `{"key1": "value1"}` the doc will just have `{"key1": "value1"}` while with update you actually have `{"key": "value", "key1": "value1"} ` – Nilan Saha May 14 '21 at 19:31
  • also what I found is that with `doc_as_upsert` via `es.update` you couldn't pass pipeline arg – Antoni4 Jul 16 '21 at 12:35