Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elastic Search Remove Elements From Nested Object

I have created an index in elastic search with a nested type field. and added documents into the index. Now I want to remove some elements from nested objects who match the condition using UpdateByQuery. I have tried the following query to but getting Conflict error.

POST test/_update_by_query
{
    "script": {
        "source": "for(int i= 0; i< ctx._source.address.size(); i++){if(ctx._source.address[i].city == params.city && ctx._source.address[i].state == params.state){ctx._source.address.remove(i)}}",
        "params": {
            "city": "Mumbai",
            "state": "Maharashtra"
        }
    },
    "query": {
        "bool": {
            "must": [{
                "term": {
                    "uid": "123"
                }
            }]
        }
    }
}

We have multiple documents whose uid is "123" Is any other option to remove elements from a nested object without getting a Conflict error? How I can solve this kindly Help me here.

like image 371
Suraj Dalvi Avatar asked Jun 22 '26 02:06

Suraj Dalvi


1 Answers

You need to do it like this:

POST test/documents/_update_by_query
{
    "script": {
        "source": "ctx._source.address.removeIf(a -> a.city == params.city && a.state == params.state)",
        "params": {
            "city": "Mumbai",
            "state": "Maharashtra"
        }
    },
    "query": {
        "bool": {
            "must": [{
                "term": {
                    "uid": "123"
                }
            }]
        }
    }
}
like image 144
Val Avatar answered Jun 25 '26 04:06

Val



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!