17

I want to send n upsert partial requests to ES, is such a thing possible? So if the document doesn't exist, insert my partial doc. If it already exists, update it with the partial doc.

Using the bulk helpers, I've tried a ton of variations, but they all wipe out existing values in favour of the new ones.

data = [{
    "_index": 'my_index',
    "_type": 'my_type',
    "_id": 12345,
    "doc": {"newkey": 'newvalue'}
}]
helpers.bulk(es, data, index='my_index', doc_type='my_type')

or

data = [{
    "_index": 'my_index',
    "_type": 'my_type',
    "_id": 12345,
    "_source": {"newkey": 'newvalue'}
}]
helpers.bulk(es, data, index='my_index', doc_type='my_type')

Does not work either.

2 Answers 2

17

As J. Ku answered, he has given the right answer but the code provided is incomplete. So posting the complete answer.

data = [{
    "_op_type": 'update',
    "_index": 'my_index',
    "_type": 'my_type',
    "_id": 12345,
    "doc": {"newkey": 'newvalue'},
    "doc_as_upsert":True
}]

helpers.bulk(es, data, index='my_index', doc_type='my_type')
Sign up to request clarification or add additional context in comments.

2 Comments

what if you dont know the _id?
Haven't worked on elastic search for a long time. However I feel, _id is necessary in upsert, else you cannot identify whether the doc is there or not. And if you don't know it, you have to make another query to fetch all the ids you want to update.
1

I think you need to include the action as mentioned in the documentation and set upsert as true

data = [{
    "_op_type": 'update',
    "_index": 'my_index',
    "_type": 'my_type',
    "_id": 12345,
    "doc": {"newkey": 'newvalue'}
}]
helpers.bulk(es, data, index='my_index', doc_type='my_type')

4 Comments

doc_as_upsert does not make a difference. Also I want the action to be index, which is default if you leave it out. Finally, I'm using the bulk API which is different syntax from what you posted.
I believe the index action always overwrites the existing value if exist.
not sure how to do it with index. my answer uses update and it would behave like you expected
sorry, I had the syntax wrong, I think the above works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.