I got it. This works. But it seems dirty and performance intensive
{
"script": {
"lang": "painless",
"source": """
ctx.to_keep = new ArrayList();
ctx.to_drop = new ArrayList();
ctx.to_keep = ['field1', 'field2'];
for (key in ctx.keySet()) {
if (! ctx.to_keep.contains(key)) {
ctx.to_drop.add(key);
}
}
for (key in ctx.to_drop) {
ctx.remove(key);
}
"""
}
I am not sure how efficient this is. Can someone from elastic please take a look here ?