简体   繁体   English

弹性搜索中出生日期字段的部分日期搜索

[英]Partial date search on Date Of Birth Fields in Elastic Search

I have one field which is dateofbirth whose mapping is something like below "dateofbirth": { "type": "date", "fields": { "tokens": { "type": "text" } }, "ignore_malformed": true, "format": "yyyy-MM-dd" }, I have a use case where i need to search on the basis of yyyydd & yyyy & yyyyMM, Does any one know how to apply analyzer in such case, so that tokens can be created for searching.我有一个字段是 dateofbirth,它的映射如下所示 "dateofbirth": { "type": "date", "fields": { "tokens": { "type": "text" } }, "ignore_malformed": true, "format": "yyyy-MM-dd" },我有一个用例,我需要根据 yyyydd & yyyy & yyyyMM 进行搜索,有谁知道在这种情况下如何应用分析器,以便令牌可以创建用于搜索。

There are many ways to resolve above.上面有很多方法可以解决。

  1. Create additional fields for year, month and day为年、月和日创建附加字段
{
  "mappings": {
    "properties": {
      "dateofbirth": {
        "type": "date",
        "fields": {
          "tokens": {
            "type": "text"
          }
        },
        "ignore_malformed": true,
        "format": "yyyy-MM-dd"
      },
      "year":{
        "type": "integer"
      },
      "month":{
        "type": "integer"
      },
      "day":{
        "type": "integer"
      }
    }
  }
}

You can query it using multiple term clauses based on format you need您可以根据您需要的格式使用多个术语子句来查询它

{
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "year": {
              "value": "VALUE"
            }
          }
        },
        {
          "term": {
            "month": {
              "value": "VALUE"
            }
          }
        }
      ]
    }
  }
}
  1. Using range query.使用范围查询。 For yyyydd对于年年日
{
   "query": {
     "bool": {
        "must": [
          {
           "range": {
             "dateofbirth": {
               "gte": "2019-01-05",
               "lte": "2019-12-31"
             }
           }
          }
        ]
     }
   }
}

For year range will 2019-01-01 & 2019-12-31., for yyyyMM range will 2019-10-01 and 2019-10-31年份范围为 2019 年 1 月 1 日和 2019 年 12 月 31 日,yyyyMM 范围为 2019 年 10 月 1 日和 2019 年 10 月 31 日

  1. Using script使用脚本
{
   "query": {
     "bool": {
        "must": [
          {
            "script": {
              "script": {
                "source": "int year = doc['dateofbirth'].value.getYear();int month = doc['dateofbirth'].value.getMonthValue();int day = doc['dateofbirth'].value.getDayOfMonth(); if(year==params.year && month==params.month) return true;",
                "params": {
                  "year":2019,
                "month":10
                }
              }
            }
          }
        ]
     }
   }
}

Option 1 will have highest performance followed by 2 and 3.选项 1 的性能最高,其次是 2 和 3。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM