Sorting by distance from nested document with fallback to parent value

I have an index set up similar to the following mapping:

{
  "mappings": {
    "item": {
      "properties": {
        "name": {
          "type": "string"
        },
        "location": {
          "type": "geo_point",
          "lat_lon": true
        },
        "userLocation": {
          "type": "nested",
          "properties": {
            "accountId": {
              "type": "integer"
            },
            "location": {
              "type": "geo_point",
              "lat_lon": true
            }
          }
        }
      }
    }
  }
}

What I want to accomplish is to sort by distance from a given point based on the userLocation if it exists for an account, otherwise by the distance from the location on the parent item.

I can get the sort by the distance from the nested document using the following sort but can't figure out if it's possible to "fallback" to using the parent location:

{
  "_geo_distance": {
    "userLocation.location": "37.7576793,-122.5076399",
    "order": "asc",
    "nested_path": "userLocation",
    "nested_filter": {
      "term": {
        "userLocation.accountId": "12345"
      }
    }
  }
}

I've also tried sorting by using the following script but it caused higher than acceptable CPU usage when tested under load.

def location = _source.location;

def userLocation = _source.userLocation.find { ul -> ul.accountId == accountId }; 
if (userLocation) { 
    location = userLocation.location; 
}; 

return org.elasticsearch.common.geo.GeoDistance.ARC.calculate(location.lat, location.lon, origin.lat, origin.lon, org.elasticsearch.common.unit.DistanceUnit.KILOMETERS);

Is there an efficient way to sort the data by this criteria when the data is indexed this way? If not, is there a better way to organize the data to make this sort efficient?

hi,
sorry i have no idea.
All i want to say is "thank you a lot", your example helped me a lot for sorting by distance based on a nested geopoint