How to get current time as unix timestamp for script use

Hello,

I have three fields:

  • date_start (type: date)
  • date_end (type: date)
  • permanent (type: bool)

I would like to return all documents with theses conditions:
date_start <= now AND date_end >= now
OR
date_start <= now AND permanent == true

What is the best way to do that ?

I thought it would be to use a script like this :

{
 "query": {
   "bool": {
     "filter": [
       {
         "script": {
           "script": {
             "source": "((doc['date_start'].value <= params.now) && (doc['date_end'].value >= params.now)) || ((doc['date_start'].value <= params.now) && (doc['permanent'].value == params.permanent))"
           },
           "lang": "painless",
           "params": {
             "now": "1594390526",
             "permanent": true
           }
         }
       }
     ]
   }
 }
}

But there is an issue with date types comparison and I don't know how to solve this.
Thank you

@Quentin_L_eilde
Since you haven't mentioned format for the date_start and date_end, I am assuming default format which is "strict_date_optional_time||epoch_millis"

  1. However your "now" is in seconds. It should be in milliseconds.
  2. if param "now" is refers to current timestamp then you can pass word now instead of value.
  3. You can use simple range queries instead of script.
  4. Optionally you can rewrite query as ((date_start <= now) AND (date_end >= now OR permanent == true))

So you can use (now = current time)

{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "date_start": {
              "lte": "now"
            }
          }
        },
        {
          "bool": {
            "should": [
              {
                "range": {
                  "date_end": {
                    "gte": "now"
                  }
                }
              },
              {
                "term": {
                  "permanent": true
                }
              }
            ]
          }
        }
      ]
    }
  }
}

or this if now is a random time

{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "date_start": {
              "lte": 1594390526000
            }
          }
        },
        {
          "bool": {
            "should": [
              {
                "range": {
                  "date_end": {
                    "gte": 1594390526000
                  }
                }
              },
              {
                "term": {
                  "permanent": true
                }
              }
            ]
          }
        }
      ]
    }
  }
}
1 Like

hey !

Thanks for the answer it solves my issue :wink:

Thanks

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