Rahul Saini
Rahul Saini

Reputation: 937

How to use date filter in elasticsearch

I am using the client object of elasticsearch.

var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
    host:"https://********",
    log: 'trace',
});


"hits": [
        {
            "_index": "abc",
            "_type": "_doc",
            "_id": "39KueHEBnbKK-Fpwq9wG",
            "_score": 1.0,
            "_source": {
                "videoId": "EV-IOHABXh-qOCdiWVbW",
               "createddate": "2020-04-14 18:04:05"


            }
        },
        {
            "_index": "abc",
            "_type": "_doc",
            "_id": "29KueHEBnbKK-Fpwq9wG",
            "_score": 1.0,
            "_source": {
                "videoId": "zV-IOHABXh-qOCdiWVbW",
                 "createddate": "2020-03-14 18:04:05",


            }
        }
    ]

I am trying to filter based on createddate. This is my query which I am trying to filter out the data but not working. Please help me.

Note: I need to filter data between two dates.

{
   "query": {
    "bool": {
        "filter": [
            {

                "range": {
                    "createddate": {
                        "gte": "2020-04-11 00:00:00",
                        "lte": "2020-04-16 23:59:59"
                    }
                }
            }
        ]
    }
}

}

Upvotes: 1

Views: 79

Answers (1)

Bhavya
Bhavya

Reputation: 16172

Mapping:

{
  "mappings": {
    "properties": {
      "createddate": {
        "type": "date",
        "format":"yyyy-MM-dd HH:mm:ss"
      }
    }
  }
}

Indexed two documents

{
    "videoId": "EV-IOHABXh-qOCdiWVbW",
    "createddate":"2020-04-14 18:04:05"
 }

 {
 "videoId": "zV-IOHABXh-qOCdiWVbW",
 "createddate": "2020-03-14 18:04:05"
 }

Same Search Query which you provided:

{
   "query": {
    "bool": {
        "filter": [
            {

                "range": {
                    "createddate": {
                        "gte": "2020-04-11 00:00:00",
                        "lte": "2020-04-16 23:59:59"
                    }
                }
            }
        ]
    }
}
}

Result:

"hits": [
         {
            "_index": "test",
            "_type": "_doc",
            "_id": "1",
            "_score": 0.0,
            "_source": {
               "videoId": "EV-IOHABXh-qOCdiWVbW",
               "createddate": "2020-04-14 18:04:05"
            }
         }
      ]

The search query filters the data between the two dates, and gives out the expected result.

Upvotes: 1

Related Questions