Update only specific field value in elasticsearch
Solution 1:
As a codebased contribution to this answer, the following query may be used:
POST /index/type/100100471/_update
{
"doc" : {
"yourProperty" : 10000
}
}
This query updates yourProperty
property only.
As a result, this response appears:
{
"_index": "index",
"_type": "type",
"_id": "100100471",
"_version": 1,
"_shards": {
"total": 0,
"successful": 1,
"failed": 0
}
}
Solution 2:
In ES 7.3 the new format is:
POST /myindex/_update/mydocid
{
"doc" : {
"myfield": "new value of my field"
}
}
Solution 3:
Yes, Elasticsearch supports partial updates. That means that you can submit:
- a partial document, which will be merged with the existing one
- a script that will be executed on top of the existing document
Have a look at the update api. In both cases, what happens under the hood, due to how the underlying lucene library works, is that the document to be updated is retrieved, the changes are applied to it, and the old document gets overwritten with the new. At the end of the day it is in fact a complete rewrite of the document, but you don't have to submit the whole document, unless you disabled the _source field, enabled by default, which is the field that allows you to retrieve to whole document in order to apply changes to it.
Solution 4:
If you would like to update the existing field value only then you must try this solution:
POST IndexName/_update_by_query
{
"script": {
"source": """
if (ctx._source?.Field != null)
{
ctx._source.remove('Field');
ctx._source.put('Field', 'Value');
}
""",
"lang": "painless"
},
"query": {
"terms": {
"_id": [
1 (Replace with Document ID)
]
}
}
}
If you would like to add new field with value then you must try this solution:
POST IndexName/_update_by_query
{
"script": {
"source": """
if (ctx._source?.NewField == null)
{
ctx._source.hf.put('NewField', 'Value');
}
""",
"lang": "painless"
},
"query": {
"terms": {
"_id": [
1 (Replace with Document ID)
]
}
}
}