5
votes

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.

1
What does this question have to do with Go?Adrian

1 Answers

7
votes

You can do this with filter clause:

{
  "query": {
    "bool": {
      "filter": [
        {
          "range": {
            "startDate": {
              "lte": "<startDate>"
            }
          }
        },
        {
          "range": {
            "endDate": {
              "gte": "<endDate>"
            }
          }
        }
      ]
    }
  }
}