1
votes

I'm getting this error when trying to match all in my index, and display the distance between a given geo_point and the query results, I'm using DrTech's answer for the script to display the distance:

this is my DSL query:

{
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "distance": {
      "lang": "groovy",
      "params": {
        "lat": 2.27,
        "lon": 50.3
      },
      "script": "doc['geo_coordinates'].distanceInKm(lat,lon)"
    }
  }
}

Query response:

{
  "took": 50,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 4,
    "failed": 1,
    "failures": [
      {
        "shard": 0,
        "index": "users",
        "node": "pa76fjdWQl2YAHmgCT4oKw",
        "reason": {
          "type": "script_exception",
          "reason": "failed to run inline script [doc['geo_coordinates'].distanceInKm(lat,lon)] using lang [groovy]",
          "caused_by": {
            "type": "null_pointer_exception",
            "reason": null
          }
        }
      }
    ]
  },
  "hits": {
    "total": 184,
    "max_score": 1,
    "hits": []
  }

and I have this in my mapping :

  "geo_coordinates" : {
            "type" : "geo_point",
            "lat_lon" : true
          },

so I don't understand why I'm getting a Null pointer !! .....

1
Is it possible that one of your documents has no geo_coordinates field ?Val
Impossible it does exist in my Mongodb and in my Elasticsearch mappingZEE
I'm not talking about the mapping, but if you just have one single document instance which doesn't have any value for this field, that might explain the NPE.Val
yes some users have this field without any value !ZEE
There you go, then you should modify your script to only call distanceInKm() if the value exists.Val

1 Answers

5
votes

It's probably because one of the documents doesn't have any value in the geo_coordinates field. Hence, you need to account for this case in your script.

Try this instead:

{
  "query": {
    "match_all": {}
  },
  "script_fields": {
    "distance": {
      "lang": "groovy",
      "params": {
        "lat": 2.27,
        "lon": 50.3
      },
      "script": "doc['geo_coordinates'] ? doc['geo_coordinates'].distanceInKm(lat,lon) : 0"
    }
  }
}