Elasticsearch date query. People who were born in a certain month

▼魔方 西西 提交于 2019-12-24 11:26:51

问题


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:


Just for the archives, ES 7 brought some braking changes https://www.elastic.co/guide/en/elasticsearch//reference/current/breaking-changes-7.0.html#_getdate_and_getdates_removed

It is now:

POST /people/_search?size=50
{
  "query": {
    "bool" : {
      "filter" : {
       "script" : {
          "script" : {
            "source": "doc['jour'].value.getMonthValue() == 5",
            "lang": "painless"
          }
        }
      }
    }
  }
}



回答4:


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



来源:https://stackoverflow.com/questions/32640437/elasticsearch-date-query-people-who-were-born-in-a-certain-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!