Unable to get results using date as string field

Hi All,

I have created a string field and inserting the date value in [yyyy-mm-dd] format. As per my requirement i can't change the field type to date.When i try to search data using the range query it is not giving the results between two dates.

PUT testdate
 {
   "mappings": {
      "documents": {
        "dynamic" : "strict",
         "properties": {
           "name":{
             "type": "string"
           },
           "cdate":{
             "type": "string"
           }
         }
      }
   }
}

POST testdate/documents/_bulk
{ "index": { "_id": 1 }}
{ "name" : 10, "cdate" : "2001-01-01" }
{ "index": { "_id": 2 }}
{ "name" : 20, "cdate" : "2001-01-11" }
{ "index": { "_id": 3 }}
{ "name" : 30, "cdate" : "2001-01-25" }

Query

{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "cdate": {
              "from": "2001-01-01",
              "to": "2002-02-02"
            }
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 10,
  "sort": [],
  "facets": {}
}

when i tried it is giving wrong data.

please help me.

First you should use a date type. BTW, elasticsearch would autodetect this as dates if you don't specify a mapping.

Coming back to your question, as your String uses the default analyzer, your text 2001-01-01 has been broken into [2001, 01, 01]. Which gives here inaccurate results or no result at all. If you really want to do it using strings, you have to set index: not_analyzed on your field.

My 2 cents

thank you for reply.

is there any difference the way we define mappings for the index. in the above example for "cdate" mapping structure is like...

"properties": {
"cdate":{
"type": "string",
"index":"not_analyzed"
}
}
able to get the exact results.

when i change the mapping as
"properties": {
"cdate": {
"type": "string",
"fields": {
"raw": {
"type": "string",
"index": "not_analyzed"
}
}
}

not able to get the proper results.

Please format your code.

If you do this, then you have to search in cdate.raw field.