Didac Montero
Didac Montero

Reputation: 2086

ElasticSearch painless script to remove all the keys except for a list of keys

I want to execute an atomic update operation on a Elasticsearch (6.1) document where I want to remove all the document except for some keys (on the top level, not nested).

I know that for removing a specific key from a document (something in the example) I can do as follows:

curl -XPOST 'localhost:9200/index/type/id/_update' -d '{
    "script" : "ctx._source.remove(params.field)",
    "params": {
      "field": "something"
    }
}'

But what If I want to remove every field except for a field called a and a field called b?

Upvotes: 1

Views: 2143

Answers (1)

Didac Montero
Didac Montero

Reputation: 2086

I found a way to make it work. I'm posting it here since it might be useful for someone else:

POST /index/type/id/_update
{
    "script" : {
        "source" : "Object var0 = ctx._source.get(\"a\"); Object var1 = ctx._source.get(\"b\"); ctx._source = params.value; if(var0 != null) ctx._source.put(\"a\", var0); if(var1 != null) ctx._source.put(\"b\", var1);",
        "params": {
            "value": {
                "newKey" : "newValue"
            }
        }
    }

}

This script is updating the document with the content inside params.value while keeping the keys a and b from the previous version of the document. This approach is simpler for my use case since the list of keys to keep is going to be small compared to the amount of keys are present in the existing document.

If you would like only to keep the keys a and be you would first store the keys in variables, then do ctx._source.clear() and then you will add the keys back.

Upvotes: 4

Related Questions