日期字段的Elasticsearch部分匹配

时间:2020-05-16 19:03:52

标签: datetime elasticsearch

我有100条记录属于2020-05-01,所以一旦键入2020,是否有可能返回包括2020在内的所有记录?

1 个答案:

答案 0 :(得分:0)

您可以使用范围来过滤日期字段

{
  "query": {
    "bool": {
      "filter": {
        "range": {
          "date": {
            "gte": "2020||/y",
            "lte": "2020||/y",
            "format": "yyyy"
          }
        }
      }
    }
  }
}

您可以创建一个类型为text的子字段,该字段将以不同的令牌分隔日期,并允许您使用前缀和匹配查询

映射:

{
  "mappings": {
    "properties": {
      "date": {
        "type": "date",
        "format": [
          "yyyy-MM-dd"
        ],
        "fields": {
          "text": {
            "type": "text"
          }
        }
      }
    }
  }
}

查询:

{
  "query": {
    "match_phrase_prefix": {
      "date.text": "202"
    }
  }
}

结果:

"hits" : [
      {
        "_index" : "index43",
        "_type" : "_doc",
        "_id" : "T9RwJXIBEIlbGJUZH3VX",
        "_score" : 0.6931471,
        "_source" : {
          "date" : "2020-06-01"
        }
      }
    ]

您将需要根据您的要求混合查询文字类型或日期

相关问题