1

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 !! .....

6
  • Is it possible that one of your documents has no geo_coordinates field ? Commented Jun 15, 2016 at 13:13
  • Impossible it does exist in my Mongodb and in my Elasticsearch mapping Commented Jun 15, 2016 at 13:13
  • 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. Commented Jun 15, 2016 at 13:14
  • yes some users have this field without any value ! Commented Jun 15, 2016 at 13:15
  • There you go, then you should modify your script to only call distanceInKm() if the value exists. Commented Jun 15, 2016 at 13:16

1 Answer 1

5

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"
    }
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

"doc['geo_coordinates']?.distanceInKm(lat,lon) ?: 0" should work as well
True, that's a shorter groovy way of achieving the same thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.