Searching Date Field value in ElasticSearch without time

Mukesh picture Mukesh · Aug 11, 2015 · Viewed 7.8k times · Source

I have one date field in my data as

"type": "date",
"format": "dateOptionalTime"

Now My date Field and Value is -

"INITIAL_EXTRACT_DATE" : "2015-04-02T06:47:57.78+05:30"

While searching I am searching based on only date that is "2015-04-02". but I am getting 0 result.

Can anyone suggest how to search exact date and is any of date.

Now I am trying with this -

For Exact Date -

"term": {
          "IH_PT_DSC": {
             "value": "2015-04-02"
          }
       }

For Is any of date -

"terms": {
         "IH_PT_DSC": [
            "2015-04-02",
            "2015-04-03",
            "2015-04-03"
         ]
      }

Answer

Val picture Val · Aug 11, 2015

You can use a range filter for this, by using the same date in gte / lte and a format parameter where you only specify the date part (i.e. leave out the time part)

{
    "constant_score": {
        "filter": {
            "range" : {
                "IH_PT_DSC" : {
                    "gte": "2015-04-02",
                    "lte": "2015-04-02",
                    "format": "yyyy-MM-dd"
                }
            }
        }
    }
}

If you need to specify multiple dates, you can do so easily as well.

{
    "constant_score": {
        "filter": {
            "range" : {
                "IH_PT_DSC" : {
                    "gte": "2015-04-01",
                    "lte": "2015-04-03",
                    "format": "yyyy-MM-dd"
                }
            }
        }
    }
}

Finally, if you need to query disjoint date intervals, simply use a bool/should filter:

{
  "constant_score": {
    "filter": {
      "bool": {
        "should": [
          {
            "range": {                    <--- interval 1
              "IH_PT_DSC": {
                "gte": "2015-04-01",
                "lte": "2015-04-03",
                "format": "yyyy-MM-dd"
              }
            }
          },
          {
            "range": {                    <--- interval 2
              "IH_PT_DSC": {
                "gte": "2015-04-05",
                "lte": "2015-04-08",
                "format": "yyyy-MM-dd"
              }
            }
          },
          {
            "range": {                    <--- interval 3
              "IH_PT_DSC": {
                "gte": "2015-04-10",
                "lte": "2015-04-12",
                "format": "yyyy-MM-dd"
              }
            }
          }
        ]
      }
    }
  }
}