user2626210
user2626210

Reputation: 125

range between two dates in elastic Search

i have a question with filter, range and or with elastic search.

I have de document in elasticSearch with

    {
      startDate : myDate
      endDate : onOtherDateOr Nothing

    }

I Want to search for a range where now is after startDate, or Between startDate and endDate if endDate is defined. How can i do that ?

Upvotes: 1

Views: 10704

Answers (3)

A. chahid
A. chahid

Reputation: 303

try the next query, at least it works for me.`

"query": {
    "range": {
        "date_ field ": {  # this field_name should be the field where your date range 
                                        resides. 
                 "gte": startDate,
                  "lte": endDate,
                   "boost": 2.0
                      }
                    }
                  }`

Upvotes: 0

Aditya Bittu
Aditya Bittu

Reputation: 59

I find below query as best approach:

{
  "query": {
    "range": {
      "order.dateCreated": {
        "dateFrom": "2011-01-24",
        "dateTo": "2011-01-24"
      }
    }
  }
}

Upvotes: 3

Val
Val

Reputation: 217254

You can do it like this with two bool/should filters containing two nested bool/must filters:

curl -XPOST localhost:9200/_search -d '{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "should": [
            {
              "bool": {
                "must": [            <--- if endDate exists, check both bounds
                  {
                    "exists": {
                      "field": "endDate"
                    }
                  },
                  {
                    "range": {
                      "startDate": {
                        "lte": "now"
                      }
                    }
                  },
                  {
                    "range": {
                      "endDate": {
                        "gte": "now"
                      }
                    }
                  }
                ]
              }
            },
            {
              "bool": {
                "must": [            <--- if endDate missing, only check startDate
                  {
                    "missing": {
                      "field": "endDate"
                    }
                  },
                  {
                    "range": {
                      "startDate": {
                        "lte": "now"
                      }
                    }
                  }
                ]
              }
            }
          ]
        }
      }
    }
  }
}'

Upvotes: 2

Related Questions