How copy values from included object to root _source

Hi there!
my _source is

"_source": {
                    "a": "",
                    "loc": {
                        "latitude": 74.638405,
                        "longitude": 29.701075
                    },
                    "@timestamp": "2024-11-05T12:59:54.309647711Z",
                    "@version": "1",
                }

I trying to copy latitude/longitude from included object “loc” to root “_source” but got null_pointer_exception, cannot access method/field [latitude] from a null def reference

POST locindex/_update_by_query
{
  "script": {
    "lang": "painless", 
    "source": "ctx._source.lat = ctx._source.loc.latitude; ctx._source.lon = ctx._source.loc.longitude"
  }
}

what am I doing wrong? and how copy latitude/longitude from included object “loc” to root “_source” ?

Thanks in advance.

Hi @ser, do all your documents contain the latitude field?
You can check if adding a condition would bypass the error.

POST locindex/_update_by_query
{
  "script": {
    "lang": "painless",
    "source": """
      if (ctx._source.loc != null && ctx._source.loc.latitude != null && ctx._source.loc.longitude != null) {
        ctx._source.lat = ctx._source.loc.latitude;
        ctx._source.lon = ctx._source.loc.longitude;
      }
      """
  }
}