14

How to remove arraylist values in Elasticsearch using sense console or curl?

i want to remove any array element.?

POST /q/q/
{
    "a": [
    "z", "q", "1"
    ]
}

it doesnt work for me:

POST /q/q/AV4sjk40mWHLgYFNkmNd/_update
{
    "script": {
        "lang": "painless",
        "inline": "ctx._source.a -=newsupp",
        "params": {
            "newsupp": "p" 
        }
     }
}

or

POST /q/q/AV4sjk40mWHLgYFNkmNd/_update
{
    "script": {
        "lang": "painless",
        "inline": "ctx._source.a.remove("1")"
    }
}
alexbt
  • 16,415
  • 6
  • 78
  • 87
bala s
  • 159
  • 1
  • 2
  • 7
  • Try with single quotes, instead `"ctx._source.a.remove('1')"` – Val Aug 31 '17 at 11:19
  • "ctx._source.a.remove('1')" throwing error: "script": "ctx._source.a.remove('z')", "lang": "painless", "caused_by": { "type": "wrong_method_type_exception", "reason": "cannot convert MethodHandle(List,int)Object to (Object,String)Object" } } }, – bala s Aug 31 '17 at 12:47
  • 9
    Sorry, try this instead `"ctx._source.a.removeIf(e -> e.equals('1'))"` – Val Aug 31 '17 at 13:32

1 Answers1

29

If you want to remove all occurrences in the list, you can do this:

{
  "script": {
    "lang": "painless",
    "inline": "ctx._source.a.removeAll(Collections.singleton('1'))"
  }
}

or if you want to remove just the first, like this:

{
  "script": {
    "lang": "painless",
    "inline": "ctx._source.a.remove(ctx._source.a.indexOf('1'))"
  }
}

Also note that if you want to use double-quotes, it's fine, but you need to escape them, like ctx._source.a.indexOf(\"1\")).

Or with params:

{
  "script": {
    "lang": "painless",
    "inline": "ctx._source.a.remove(ctx._source.a.indexOf(yourParamName))",
    "params": {
      "yourParamName": "1"
    }
  }
}
dshockley
  • 1,494
  • 10
  • 13
  • 2
    Thanks @dshockley this worked great. Although, I did have to make one small change. I had to reference my param name by using 'params.yourParamName' like this `ctx._source.a.remove(ctx._source.a.indexOf(params.yourParamName))` – Fabian Mar 28 '18 at 19:13
  • Any way to remove values based on wild card? – Kieran Quinn Jul 02 '20 at 15:38
  • 1
    Will indexOf return -1 if index does not exists? – Vingtoft Sep 18 '20 at 09:33