I have a mapping with 2 fields: message + weight.
'Message' is unique for each document.
I have to increment 'weight' each time document is retrieved.
If not found, I have to insert new document with default values.
Is there any way to automatically insert document, if not found, while running _update_by_query?
POST /testindex/_update_by_query?conflicts=proceed
{
"script": {
"inline": "ctx._source.weight++",
"lang": "painless"
},
"query": {
"match": {
"message": "iphone"
}
}
}
I need it to function like SQL: INSERT… ON DUPLICATE KEY UPDATE
Since your message
field is unique for all documents, you can use it as the document ID. That would enable you to leverage the Update API and more specifically the upsert feature.
Basically, you can update a document (increment the weight
) and if it doesn't exist it gets created (with weight: 1
):
POST testindex/_doc/iphone/_update
{
"script" : {
"source": "ctx._source.weight++",
"lang": "painless"
},
"upsert" : {
"weight" : 1
}
}