user706838
user706838

Reputation: 5380

How to insert new or update old document using elasticsearch-py?

What is the most elegant way to insert a new document (if not already exists) or update (increase counter by 1) of an already existed document?

This one:

res = elasticsearch.update(
        index='stories-test',
        doc_type='news',
        id=1,
        body={
            "doc":
                {
                    "author": "me",
                    "visits": 1
                },
                'doc_as_upsert': True
        },
        script={
                    "inline": "ctx._source.visits += visit",
                    "params": {
                        "visit": 1
                    }
        }
    )

Troughs the following error:

RequestError: TransportError(400, u'action_request_validation_exception', u"Validation Failed: 1: can't provide both script and doc;")

Upvotes: 3

Views: 1588

Answers (2)

tmin
tmin

Reputation: 1323

You can include "doc" field in the body to update.

es = Elasticsearch()
doc = NewsSerializer(news).data
es.update(index="news_index", doc_type='news', id=1, body={"doc": doc})

Upvotes: 1

Adrien Chaussende
Adrien Chaussende

Reputation: 361

You can't use the update query with both doc and script params. You can do all the stuff in the script field using the params field in it.

You may find more information in this post:

Elastic Search Partial Update

Upvotes: 0

Related Questions