如何使用 ElasticSearch 按日期排序

Gli*_*ome 1 elasticsearch

我有一个带有date字段的索引,如下所示:

{
  "properties": {
    "productCreationDate": {
      "format": "YYYY-MM-dd'T'HH:mm:ssXXX",
      "type": "date"
    },
  }
}
Run Code Online (Sandbox Code Playgroud)

当我以这种方式执行搜索时:

{
  "size": 5,
  "from": 0,
  "sort": [
    {
      "productCreationDate": {
        "order": "desc"
      }
    }
  ],
  "track_scores": false
}
Run Code Online (Sandbox Code Playgroud)

我按插入顺序获取文档并注意 ElasticSearch 7.9 上的字段顺序:

{
  "took": 24,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 6,
      "relation": "eq"
    },
    "max_score": null,
    "hits": [
      {
        "_index": "my-index",
        "_type": "_doc",
        "_id": "product^14",
        "_score": null,
        "_source": {
          "productCreationDate": "2020-08-14T18:21:51+02:00",
        },
        "sort": [
          1577722911000
        ]
      },
      {
        "_index": "my-index",
        "_type": "_doc",
        "_id": "product^28",
        "_score": null,
        "_source": {
          "productCreationDate": "2020-08-28T18:21:51+02:00",
        },
        "sort": [
          1577722911000
        ]
      },
      {
        "_index": "my-index",
        "_type": "_doc",
        "_id": "product^19",
        "_score": null,
        "_source": {
          "productCreationDate": "2020-08-19T18:21:51+02:00",
        },
        "sort": [
          1577722911000
        ]
      },
      {
        "_index": "my-index",
        "_type": "_doc",
        "_id": "product^27",
        "_score": null,
        "_source": {
          "productCreationDate": "2020-08-27T18:21:51+02:00",
        },
        "sort": [
          1577722911000
        ]
      },
      {
        "_index": "my-index",
        "_type": "_doc",
        "_id": "product^26",
        "_score": null,
        "_source": {
          "productCreationDate": "2020-08-26T18:21:51+02:00",
        },
        "sort": [
          1577722911000
        ]
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

我想念什么?

编辑:感谢@zaid warsi 和@Yeikel,我已将格式更改为,yyyy并且有一个新订单:

  • 15
  • 26
  • 27
  • 19
  • 28
  • 14

这更奇怪,因为我要了 5 个文件。

小智 5

YYYY 不是 Elasticsearch 中正确的内置年份格式。

尝试将您的日期格式更改为yyyy-MM-dd'T'HH:mm:ssXXX,它应该可以工作。 请参阅此处了解有效的内置日期格式,或者您可能需要在映射中定义自己的日期格式。