Query by distance performance is low

My search condition is using location to search objects around user.
Search range is calculated dynamically. CPU is very high.
What can i do to get better performance

{
    "query": {
        "bool": {
            "filter": [
                {
                    "match": {
                        "title": "cyber"
                    }
                },
                {
                    "script": {
                        "script": {
                            "source": "if(doc['effectiveArea'].size() != 0 || doc['location'].size() == 0)                {for (int i = 0; i < doc['effectiveArea'].size(); i++) {                  if (params.areaList.contains(doc['effectiveArea'][i]))                  return true;                } return false;                }                return (doc['location'].arcDistance(params.lat,params.lon) < doc['weight'].value *100)",
                            "lang": "painless",
                            "params": {
                                "areaList": [],
                                "lon": 120.5555,
                                "lat": 35.55555
                            }
                        }
                    }
                }
            ]
        }
    }
}

If you need to search objects around the user, why not use a geo point and a geo_distance query?

I see that the script is using some weight, but maybe you can first filter by geo distance and then do the costly script query, which needs to be computed for every document that matches cyber. This would reduce the number of documents for the script query a lot.

1 Like

Thank you. I will try.