Elasticsearch date query. People who were born in

2019-09-19 23:10发布

问题:

I have a field with the following mapping:

birthdate: { type: :date, format: :dateOptionalTime }
  1. I need to find everyone who were born in month of May (including all years)
  2. Another query is to find all people who were born on 'August 25' (including all years)

What would be the query for that?

回答1:

You can achieve this with a script filter

All people born in May of any year:

{
  "query": {
    "filtered": {
      "filter": {
        "script": {
          "script": "doc.birthdate.date.monthOfYear == 5"
        }
      }
    }
  }
}

All people born on August 25th (any year)

{
  "query": {
    "filtered": {
      "filter": {
        "script": {
          "script": "doc.birthdate.date.monthOfYear == 8 && doc.birthdate.date.dayOfMonth == 25"
        }
      }
    }
  }
}


回答2:

GET index_name/doc_type/_search
{
    "query": {
        "bool" : {
            "filter" : {
                "script" : {
                    "script" : {
                        "source": "doc.field_name.date.getMonthOfYear() == month_number",
                        "lang": "painless"
                     }
                }
            }
        }
    }
}


回答3:

First question:

POST /test_index/_search
{
   "query": {
      "filtered": {
         "filter": {
            "range": {
               "birthdate": {
                  "gte": "2015-05-01",
                  "lt": "2015-06-01"
               }
            }
         }
      }
   }
}

Second question:

POST /test_index/_search
{
   "query": {
      "filtered": {
         "filter": {
            "range": {
               "birthdate": {
                  "gte": "2015-08-25",
                  "lte": "2015-08-25"
               }
            }
         }
      }
   }
}

Here's the code I used to test it:

http://sense.qbox.io/gist/36c800cabbe4143ecf72144d02e58e267c1e761a