G2K
G2K

Reputation: 27

Elasticsearch painless Query to compare date field value with user input date value

ES index field for a date type looks like

"docdate" : { "type" : "date", "fields" : { "text" : { "type" : "text", "analyzer" : "autocomplete" } } }

query should check the docdate value with user input param value passed through query as below.

                "script": {
                    "script": {
                        "source": "def effecDate=doc['docdate'].value; def sf = new SimpleDateFormat('yyyy-MM-dd'); (sf.parse(params.userdate).after(sf.parse(effecDate)) || (sf.parse(params.userdate) == sf.parse(effecDate)) ",
                        "lang": "painless",
                        "params": {
                            "userdate": "2020-12-01"
                        }
                    }
                }

getting below casting error.

class_cast_exception: Cannot cast org.elasticsearch.script.JodaCompatibleZonedDateTime to java.lang.String

how to achive this query. no data type to field should be added

Upvotes: 0

Views: 4633

Answers (1)

Val
Val

Reputation: 217434

You can do it like this:

{
  "query": {
    "script": {
      "script": {
        "source": """
           def effecDate = doc['effdate'].value.toInstant(); 
           def pickupDate = Instant.parse(params.pickUpDate + 'T00:00:00Z');
           return ChronoUnit.DAYS.between(effecDate, pickupDate) >= 0;
        """,
        "lang": "painless",
        "params": {
          "pickUpDate": "2019-03-01"
        }
      }
    }
  }
}

Upvotes: 3

Related Questions