Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch date range query using two fields

I'm storing documents with two fields, startDate and endDate. I want to run Elastic queries with an input date and return all documents whose startDate and endDate contain this date. For example,

doc1:
"_source": {
     "startDate": "2015-01-01",
     "endDate": "2015-01-10"
}

If I search with an input date of 2015-01-02, this document should appear in the results because the input date falls in the range of the start and end date fields.

I'm able to do a range query using one field, but I don't know how to use two date fields since range only accepts one:

{
    "query": {
        "range" : {
            "startDate" : {
                "lte": "2015-01-02"
            }
        }
    }
}

I need to also perform a range query with "endDate" set to "gte" on that same date. That would establish the time range that I need to check. Any advice would be appreciated.

EDIT: I eventually want to convert this into Elasticsearch queries in Go using olivere's elastic library.

like image 921
covfefe Avatar asked Feb 13 '18 20:02

covfefe


1 Answers

You can do this with filter clause:

{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "startDate": {
              "lte": "<startDate>"
            }
          }
        },
        {
          "range": {
            "endDate": {
              "gte": "<endDate>"
            }
          }
        }
      ]
    }
  }
}
like image 106
briarheart Avatar answered Nov 05 '22 01:11

briarheart