Elasticsearch date query. People who were born in

2019-09-19 23:16发布

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?

3条回答
姐就是有狂的资本
2楼-- · 2019-09-19 23:41
GET index_name/doc_type/_search
{
    "query": {
        "bool" : {
            "filter" : {
                "script" : {
                    "script" : {
                        "source": "doc.field_name.date.getMonthOfYear() == month_number",
                        "lang": "painless"
                     }
                }
            }
        }
    }
}
查看更多
Animai°情兽
3楼-- · 2019-09-19 23:43

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"
        }
      }
    }
  }
}
查看更多
你好瞎i
4楼-- · 2019-09-19 23:45

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

查看更多
登录 后发表回答