Search code examples
elasticsearchelasticsearch-5elasticsearch-painless

Elasticsearch Deleting all nested object with a specific datetime


I'm using Elasticsearch 5.6 and I have a schedule nested field with nested objects that look like this

{
              "status": "open",
              "starts_at": "2020-10-13T17:00:00-05:00",
              "ends_at": "2020-10-13T18:00:00-05:00"
            },
            {
              "status": "open",
              "starts_at": "2020-10-13T18:00:00-05:00",
              "ends_at": "2020-10-13T19:30:00-05:00"
            }

what I'm looking for is a Painless query that will delete multiple nested objects that is equals to the starts_at field. I've tried multiple ways but none worked, they run correctly but don't delete the targeted objects


Solution

  • Was able to do this with looping over it and using SimpleDateFormat

    POST index/_update_by_query
        {
        "script": {"source": "for(int i=0;i< ctx._source.schedule.length;i++){ 
                                   SimpleDateFormat sdformat = new SimpleDateFormat('yyyy-MM-dd\\'T\\'HH:mm:ss'); 
                                   boolean equalDateTime = sdformat.parse(ctx._source.schedule[i].starts_at).compareTo(sdformat.parse(params.starts_at)) == 0; 
                                   if(equalDateTime) {
                                    ctx._source.schedule.remove(i)
                                   }
                               }",
                               "params": {
                                          "starts_at": "2020-10-13T17:00:00-05:00"
                                         },
                               "lang": "painless"
        },
          "query":{
            "bool": {"must":[
              {"terms":{"_id":["12345"]}}
             ]}}
        }