Compare created_time and updated_time in elasticsearch using python

Viewed 71

I have tried this query:

body = {
    "query": {
       "bool": {
           "must_not": [{
               "match": {
                  "script": "doc['updated_time'].value == doc['created_time'].value"
                 }
          }]
       }
    }
}

And my indexed document is:

"hits" : [
      {
        "_index" : "cam_canvas_update",
        "_type" : "_doc",
        "_id" : "101",
        "_score" : 1.0,
        "_source" : {
          "created_time" : "2021-08-11T13:44:13.282406282Z",
          "updated_time" : "2021-08-11T13:44:13.285397500Z",
          "engagement" : "Ford",
          "tag_set_2" : "Renew",
          "tag_set_3" : "Disputed",
          "instance_numbers" : 1,
          "canvas_name" : "First",
          "recordid" : "ford1",
          "pf" : "C6000",
          "tag_set_1" : "Sally",
          "ldos_date" : "7/7/2018",
          "architecture" : "webex"
      }
]

I want to compare created_time and updated time of all documents and as output need only updated documents. Want to write csv only with that updated documents in elasticsearch.

1 Answers

You need to use filter and script in your query like below:

{
    "query": {
        "bool": {
            "filter": [{
                "script": {
                    "script": "doc['updated_time'].value != doc['created_time'].value"
                }
            }]
        }
    }
}

If you don't want milliseconds to be compared, you can use this script instead of previous version:

{
  "query": {
    "bool": {
      "filter": [
        {
          "script": {
            "script": {
              "inline": "doc['updated_time'].value.getMillis()/1000 != doc['created_time'].value.getMillis()/1000",
              "lang": "painless"
            }
          }
        }
      ]
    }
  }
}

Please let me know if you have any problem with this query.

Related