Search code examples
elasticsearchelasticsearch-mapping

Elasticsearch 2.x sort with missing value treated as 0.0


According to mapping the field I'm sorting on is of type double I was expecting the sort to treat missing values as 0 since I have some negative values which I expect to go below missing ones. (Currently missing goes below negative)

How do I achieve this?


Solution

  • You seem to describe that missing, or null values should be handled as 0 values. If you do not need to be able to distinguish them from actual '0' values, you can use a null_value, see the manual

    If you do, in another situation, have to distinguish them, you might need to add a flag or something (so a second field) to actually say "but this was actually missing", but that's really depending on your usecase

    a quick example:

    PUT test
    {
      "mappings": {
        "my_type": {
          "properties": {
            "status_code": {
              "type":       "integer",
              "null_value": 0 
            }
          }
        }
      }
    }
    
    PUT test/my_type/1
    {
      "status_code": null
    }
    PUT test/my_type/2
    {
      "status_code": -1
    }
    PUT test/my_type/3
    {
      "status_code": 1
    }
    
    GET test/my_type/_search
    {
        sort" : [
            { "status_code" : "desc" },
        ]
    }
    

    This will return the documents in order 2, 1, 3 as expected