1

I've the following document indexed in ElasticSearch

{
  "myObj":{
     "name": "test",
     "elements": {
        "val": 1
     }
  }
}

I want to do a partial update to empty the nested attribute elements so I should be elements": {}; So I tried to send a partial update:

POST /entities/_doc/1/_update

{
   "doc" : {
      "myObj":{
         "elements": {}  
      }
   }
}

But this does nothing and the document keeps untouched. How can I empty a nested object in a document using partial updates ?

2
  • Is it just an object or nested object? Commented Jan 24, 2019 at 16:10
  • Well, I'm not familiar with ElasticSearch terms but it is a simple attribute of my object. Like myObj.elements.val and I want it to be myObject.elements == empty Commented Jan 24, 2019 at 16:15

2 Answers 2

1

I suggest to do a scripted update like this and it will work:

POST entities/_doc/1/_update
{
   "script" : {
      "source": """
         ctx._source.myObj.elements.clear(); 
         ctx._source.myObj.name = params.name;
      """,
      "params": {
        "name": "newTest"
      }
   }
}
Sign up to request clarification or add additional context in comments.

5 Comments

But what if I want to update other fields as well ? Can I do a partial update along with this script ? Because when I tried here, I got an error Validation Failed: 1: can't provide both script and doc
You can definitely line up several updates in the script
How can I do that ? Suppose that I want to update the name attribute as well on the same request.
See my updated answer (note that the three " are intended and that's how you can send new lines separated scripts to ES and make your scripts more readable)
Thanks @Val. It works, but it is a pain when we have a more complex object. Would be great if ES provides a way to send scripts and objects together.
1

You can simply set the value as null to empty the object completely.

POST /entities/_doc/1/_update
{
   "doc" : {
      "myObj":{
         "elements": null  
      }
   }
}

4 Comments

The problem is that the elements map will be null instead of empty.
@Val But does it make a difference? In any case both are same if we consider the behaviour of exists query. Correct me if I'm wrong.
Sure, I'm just stating that given the requirements stated by the OP. Not sure what he does with the elements map next. Also, the problem is that when seeing elements: null you don't know if it was an object field or a normal field originally
@Val Agree to that. It totally depends how one is going to further use the object field. Thanks for your prompt reply.

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.