Yuk_dev
Yuk_dev

Reputation: 368

Elasticsearch query greater than date

I create an index and it save two date (D1, D2) for something, after that I want to query this monent is it between D1 and D2, so I query :

startdate <= "2019-08-22T03:55:47.165Z" AND endate>= "2019-08-22T03:55:47.165Z"

It successful return the data as I want, so I try to do the same things in Dev tools again with:

GET i_want_get_date/_search
{
  "query":{
    "query_string":{
      "query":"startdate<= \"2019-08-22T03:55:47.165Z\" AND enddate>= \"2019-08-22T03:55:47.165Z\""
    }
  }
}

The problem is:

it cannot search any result back, the query cannot compare the date using this method

Any suggestion? Thanks!

============================================================

Thanks Val answer the question, I using a very slimier query to do the same function, I change a little bit query syntax to make it works:

GET i_want_get_date/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "startdate":{
              "lte":"2019-08-22T03:55:47.165Z"
            }
          }
        },
        {
          "range": {
            "enddate":{
              "gte":"2019-08-22T03:55:47.165Z"
            }
          }
        }
      ]
    }
  }
}

Upvotes: 12

Views: 36479

Answers (4)

Val
Val

Reputation: 217594

I suggest to use two range queries instead

GET i_want_get_date/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "startdate": {
              "gte": "2019-08-21T03:55:47.165Z"
            }
          }
        },
        {
          "range": {
            "enddate": {
              "lt": "2019-08-22T03:55:47.165Z"
            }
          }
        }
      ]
    }
  }
}

Upvotes: 14

Ajit Surendran
Ajit Surendran

Reputation: 787

If nested fields, then below query will work. Make sure the schedule data type is 'date'

"query": {
    "bool": {
      "filter": {
        "nested": {
          "path": "trans",
          "query": {
            "range": {
              "trans.schedule": {
                "lte": "2023-03-23T00:35:45"
              }
            }
          }
        }
      }
    }
  }
}

Upvotes: 0

gil.fernandes
gil.fernandes

Reputation: 14641

This is the query that worked for me to select dates after based on a specific field:

{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "_kuzzle_info.createdAt": {
              "gte": "2023-01-09T13:29:27.537+00:00"
            }
          }
        }
      ]
    }
  }
}

_kuzzle_info.createdAt is the field with the date

Upvotes: 2

danish_wani
danish_wani

Reputation: 872

there is a syntax error in your answer, the elastic fields should come before the gte or lte

{
   "range": {
         "**startdate**": {
              "**lte**": "2019-08-22T03:55:47.165Z"
          }
      }
}

Upvotes: 0

Related Questions