# Remove object from list based on attribute value

**URL:** https://discuss.elastic.co/t/remove-object-from-list-based-on-attribute-value/167733
**Category:** Elasticsearch
**Tags:** painless
**Created:** [February 10, 2019, 2:27am UTC](https://discuss.elastic.co/t/remove-object-from-list-based-on-attribute-value/167733 "2019-02-10T02:27:27Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![kgeographer](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/kgeographer/32/26217_2.png) [@kgeographer](https://discuss.elastic.co/u/kgeographer)
#### Post date: [February 10, 2019, 2:27am UTC](https://discuss.elastic.co/t/remove-object-from-list-based-on-attribute-value/167733/1 "2019-02-10T02:27:27Z")

</div>

In ES 6, I have indexed the following doc:

```
PUT test/doc/_bulk?refresh
{"index":{"_id":1}}
{"prop1":"foo","prop2":[{"a":"123"},{"a":"456"}]}

```

I need to remove the element from "prop2" that has a value of "456" for "a"

The remove() method in Painless needs an index, so I can do this:

```
POST /test/1/_update
{
"script": {
"lang": "painless",
"source": "ctx._source.list.remove(ctx._source.list.indexOf(params.obj))",
"params" : {"obj" : {"a": "456"}}  
}}

```

The problem is that each object in prop2 actually has a dozen other keys with varying values - so I can't isolate the element with a param. It requires some kind of query or filter to say "delete any element that has a value of '456' for 'a'."

In Python, if I have a list like so:

```
l=[{'a': '123', "b": '321'}, {'a': '456','b':'654'}]

```

I can get the index I need using one attribute with this:

```
[l.index(x) for x in l if x['a'] == '456'][0]

```

But I can't figure out the Painless approach (don't know Java, btw). Tried several things; this fails with a script compile error:

```
POST /test/doc/1/_update
{
  "script": {
    "lang": "painless",
    "source": """
      l = ctx._source.list
      for (x in l){
        if (x['a'] == '456') {
          idx = l.indexOf(x) 
          l.remove(idx)
        }
      }
    """
}}
```

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)
#### Post date: [March 10, 2019, 2:27am UTC](https://discuss.elastic.co/t/remove-object-from-list-based-on-attribute-value/167733/2 "2019-03-10T02:27:27Z")

</div>

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