Phantom
Phantom

Reputation: 382

Elasticsearch: sorting integer desc

When sorting by integer field in elasticsearch (version "1.1.2") using query:

{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "cubicCapacity": {
        "order": "asc",
        "ignore_unmapped": true
      }
    }
  ],
  "from": 0,
  "size": 150
}

The result is correct and documents are sorted in natural order (1, 2, 5, 10)

But when trying to complete same query using "desc":

{
  "query": {
    "match_all": {}
  },
  "sort": [
    {
      "cubicCapacity": {
        "order": "desc",
        "ignore_unmapped": true
      }
    }
  ],
  "from": 0,
  "size": 150
}

The result is not correct and documents are sorted in some strange way, but expected to be (10, 5, 2, 1).

So why sorting with "desc" could not give a correct result with a natural order?

P.S. When sorting by asc/desc but with a string type (1, 10, 2, 5), "desc" however works correct (5, 2, 10, 1)

Upvotes: 2

Views: 5672

Answers (1)

Lazy Ants
Lazy Ants

Reputation: 27

you should add leading zeros to your numbers, so you will have [0001, 0010, 0002, 0005] instead of [1, 10, 2, 5]. The number of leading zeros you have add to will depend of the max value you think you will have. e.g. if you think it will be under 10 billions so you should store 0000000005 (9 zeros) instead of 5 and 0000000010 (8 zeros) instead of 10

Upvotes: 4

Related Questions