GlinesMome
GlinesMome

Reputation: 1629

How to sort by date with ElasticSearch

I have an index with a date field as following:

{
  "properties": {
    "productCreationDate": {
      "format": "YYYY-MM-dd'T'HH:mm:ssXXX",
      "type": "date"
    },
  }
}

When I perform a search that way:

{
  "size": 5,
  "from": 0,
  "sort": [
    {
      "productCreationDate": {
        "order": "desc"
      }
    }
  ],
  "track_scores": false
}

I get the documents in the inserting order an note the field order on 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
        ]
      }
    ]
  }
}

What do I miss?

Edit: Thanks to @zaid warsi and @Yeikel I have changed the format to yyyy and I have a new order:

Which is even weirder since I asked for 5 documents.

Upvotes: 1

Views: 2293

Answers (1)

Zaid Warsi
Zaid Warsi

Reputation: 421

YYYY is not a correct inbuilt year format in Elasticsearch.

Try changing your date format to yyyy-MM-dd'T'HH:mm:ssXXX, it should work. Refer this for valid inbuilt date formats, or you might need to define your own in the mapping.

Upvotes: 5

Related Questions