Elasticsearch - 使用范围查询查询确切日期时遇到问题

Elasticsearch - Trouble querying for exact date with range query

我的事件索引中有以下映射定义:

{
  "events": {
    "mappings": {
      "properties": {
        "data": {
          "properties": {
            "reportDate": {
              "type": "date",
              "format": "M/d/YYYY"
            }
         }
       }
    }
  }
}

还有一个示例文档:

{
    "_index": "events",
    "_type": "_doc",
    "_id": "12345",
    "_version": 1,
    "_seq_no": 90,
    "_primary_term": 1,
    "found": true,
    "_source": {
        "data": {
            "reportDate": "12/4/2018",
        }
    }
}

我的目标是查询准确 data.reportDate 为 12/4/2018 的文档,但是当我 运行 这个查询时:

{
    "query": {
        "range": {
            "data.reportDate": {
                "lte": "12/4/2018",
                "gte": "12/4/2018",
                "format": "M/d/YYYY"
            }
        }
    }
}

我得到的是 2018 年所有 data.reportDate 的文档,而不仅仅是 12/4/2018。我试过设置与 CONTAINS 和 WITHIN 的关系,但没有成功。有什么想法吗?

您需要将日期格式从 M/d/YYYY 更改为 M/d/yyyy。参考这个ES official documentation to know more about date formats. You can even refer to this documentation了解yyyyYYYY

的区别

yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”)

添加具有索引映射、数据、搜索查询和搜索结果的工作示例

索引映射:

{
  "mappings": {
    "properties": {
      "data": {
        "properties": {
          "reportDate": {
            "type": "date",
            "format": "M/d/yyyy"
          }
        }
      }
    }
  }
}

索引数据:

{
  "data": {
    "reportDate": "12/3/2018"
  }
}
{
  "data": {
    "reportDate": "12/4/2018"
  }
}
{
  "data": {
    "reportDate": "12/5/2018"
  }
}

搜索查询:

{
  "query": {
    "bool": {
      "must": {
        "range": {
          "data.reportDate": {
            "lte": "12/4/2018",
            "gte": "12/4/2018"
          }
        }
      }
    }
  }
}

搜索结果:

"hits": [
      {
        "_index": "65312594",
        "_type": "_doc",
        "_id": "1",
        "_score": 1.0,
        "_source": {
          "data": {
            "reportDate": "12/4/2018"
          }
        }
      }
    ]