Score 1 returned when querying geo_point with value of NULL

ElasticSearch returns a score of 1 when querying locations that have a NULL value for their location. While I would expect that when a location is NULL that the scoring function returns a value of 0.

Below I create an ElasticSearch index that contains a geo_point and I insert one element that has a valid latitude and longitude and I insert another that has a null value for its location.

PUT my_index
{
  "mappings": {
    "properties": {
      "location": {
        "type": "geo_point"
      }
    }
  }
}

PUT my_index/_doc/1
{
  "text": "Real location",
  "location": { 
    "lat": 41.12,
    "lon": -71.34
  }
}

PUT my_index/_doc/2
{
  "text": "NULL location",
  "location": null
}

The problem arises when I try to search with a scoring function (according to the documentation here: https://www.elastic.co/guide/en/elasticsearch/reference/2.4/query-dsl-function-score-query.html).

The real values will have a score between 0 and 1 (which is the expected behaviour), while the location with the NULL value will have a score of 1. I would expect it to be 0 since no location is given.

GET /hotels/_search/
{
  "query": {
    "function_score": {
      "functions": [
        {
          "gauss": {
            "location": {
              "origin": "41, -71",
              "scale": "10km"
            }
          }
        }
      ],
      "score_mode": "multiply"
    }
  }
}

How can I make sure that the score of elements with a NULL location is 0?

bump

The documentation states that if a value is missing the function will return 1 as the score: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html#_what_if_a_field_is_missing

To work around this, you could add a function that checks whether there is a value for location and, using "score_mode": "first", if there is not, assign a score of 0. Something like this:

GET my_index/_search/
{
  "query": {
    "function_score": {
      "functions": [
        {
          "filter": {
            "bool": {
              "must_not": {
                "exists": {
                  "field": "location"
                }
              }
            }
          },
          "weight": 0
        },
        {
          "gauss": {
            "location": {
              "origin": "41, -71",
              "scale": "10km"
            }
          }
        }
      ],
      "score_mode": "first"
    }
  }
}

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.