elasticsearch - 在elasticsearch中对日期字段进行部分搜索

标签 elasticsearch elasticsearch-dsl elasticsearch-date

我正在尝试在 Elasticsearch 中的日期字段上实现部分搜索。例如,如果 startDate 存储为“2019-08-28”,我应该能够在仅查询“2019”或“2019-08”或“2019-0”时检索相同的内容。

对于其他领域我正在这样做:

{
            "simple_query_string": {
              "fields": [
                "customer"
              ], 
              "query": "* Andrew *",
              "analyze_wildcard": "true",
              "default_operator": "AND"
            }}

它完美地适用于文本字段,但同样不适用于日期字段。

这是映射: {"mappings":{"properties":{"startDate":{"type":"date"}}}}

有什么方法可以实现这一点,无论是改变映射还是其他查询方法?我还发现这个讨论与弹性中的部分日期有关,不确定它是否很相关,但这里是:

https://github.com/elastic/elasticsearch/issues/45284

最佳答案

摘自ES-Docs

Internally, dates are converted to UTC (if the time-zone is specified) and stored as a long number representing milliseconds-since-the-epoch.

无法像在文本字段上那样进行搜索。但是,我们可以告诉 ES 将日期字段同时索引为日期和文本。例如

将日期字段索引为多种类型:

PUT sample
{
  "mappings": {
    "properties": {
      "my_date": {
        "type": "date",
        "format": "year_month_day",//<======= yyyy-MM-dd
        "fields": {
          "formatted": {
            "type": "text", //<========= another representation of type TEXT, can be accessed using my_date.formatted
            "analyzer": "whitespace" //<======= whitespace analyzer (standard will tokenized 2020-01-01 into 2020,01 & 01)
          }
        }
      }
    }
  }
}

POST dates/_doc
{
  "date":"2020-01-01"
}

POST dates/_doc
{
  "date":"2019-01-01"
}

使用通配符查询进行搜索:如果需要,您甚至可以在索引时使用 n-gram 来加快搜索速度。

GET dates/_search
{
  "query": {
    "wildcard": {
      "date.formatted": {
        "value": "2020-0*"
      }
    }
  }
}

关于elasticsearch - 在elasticsearch中对日期字段进行部分搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64372856/

相关文章:

elasticsearch - 将时间戳转换为日期时间以用于 Elasticsearch 聚合

elasticsearch - 获取在Logstash中安装的插件版本

couchdb - 我正在将River-couchdb与ElasticSearch一起使用,并想将其last_seq重置为0。有人知道这是否可能吗?

json - 使用 bash 脚本在超过硬盘大小时自动清除 Elasticsearch 索引

跳过 Elasticsearch 分区索引与匹配无文档查询

elasticsearch - elasticsearch如何识别哪些字段具有共同的聚合值

django - 使用 elasticsearch-dsl DocType 映射配置

python - 暂时停用Python Faceted Search中的构面