how can I upsert documents in opensearch by python api
Asked Answered
H

2

6

I tried to upsert a document to Opensearch, that means if no id exists it would insert the document, if the id already exists then it would update the document(not overwritten).

For example, if the doc already in Opensearch {"id":1,"name":"Jack"}, when I upserted {"id":1,"job":"engineer"}, the document in opensearch would become {"id":1,"name":"Jack","job":"engineer"}, not just overwritten.

I tried python index api with doc_as_upsert as following, but it failed:

pyClient.index(
            index = indexName,
            body = document,
            id = document['id'],
            refresh = True,
            doc_as_upsert = True
        )

The document object is: {"id":"123","name":"Jack","job":"Engineer"}

Hanako answered 15/9, 2022 at 16:25 Comment(2)
"I tried python index api with doc_as_upsert as following, but it failed". How exactly did it fail?Maurilla
it says: doesn't support the doc_as_upsert action.Hanako
M
3
  1. Instead of index, you should use the update method
  2. You're passing the doc_as_upsert incorrectly. The documentation for the update function highlights that fact.

The correct way to pass it would be:

document = {"id":1,"job":"engineer"}
body = {"doc": document, "doc_as_upsert": True}
pyClient.update(
            index = indexName,
            body = body,
            id = document['id'],
            refresh = True
        )
Maurilla answered 23/9, 2022 at 3:50 Comment(1)
thank you for providing the docs, they're so hard to find!Tiatiana
A
0

try with index = document['_index'],body = document[_source] instead of index = indexName,body = document

Apogee answered 16/9, 2022 at 16:27 Comment(1)
hi SRama, I didn't get your point, The document object is: {"id":"123","name":"Jack","job":"Engineer"}.Hanako

© 2022 - 2024 — McMap. All rights reserved.