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")"
    }
}
3
  • Try with single quotes, instead "ctx._source.a.remove('1')" Commented Aug 31, 2017 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" } } }, Commented Aug 31, 2017 at 12:47
  • 9
    Sorry, try this instead "ctx._source.a.removeIf(e -> e.equals('1'))" Commented Aug 31, 2017 at 13:32

1 Answer 1

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"
    }
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

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))
Any way to remove values based on wild card?
Will indexOf return -1 if index does not exists?

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.