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


(Didac) #1

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 (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?


(Arvind Rao) #2

Try this:

POST index/type/id/_update
{
   "script": {
    "inline": "Set keys = new HashSet(ctx._source.keySet()); for(fieldName in keys){ if (!fieldName.equals('a') && !fieldName.equals('b')) {ctx._source.remove(fieldName)} }",
    "lang": "painless"
  }
}

(Didac) #3

Thanks. That's an option. Since in my case the amount of keys there are in the document is much greater than the ones I want to keep, I did it this way:

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

(system) #4

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.