I am getting error while executing this script query using Nest library in .net:
new ScriptQuery
{
Lang = "painless",
Source = "(!doc[params.headquartersCoordinatesField].empty && doc[params.headquartersCoordinatesField].arcDistance(params.latitude, params.longitude) * 0.000621371 <= params.maxDistance) || (!doc[params.offices].empty && (for (def office : doc[params.offices].values){if(office.coordinates).arcDistance(params.latitude, params.longitude) * 0.000621371 < =params.maxDistance{return true;}}))",
Params = new Dictionary<string, object>
{
{"headquartersCoordinatesField", Field<Provider>(f => f.Headquarters.Coordinates)},
{"offices", Field<Provider>(f => f.Offices)},
{"latitude", _latitude},
{"longitude", _longitude},
{"maxDistance", 50}
}
}
This is the error I get : ServerError: Type: search_phase_execution_exception Reason: "all shards failed" CausedBy: "Type: script_exception Reason: "compile error" CausedBy: "Type: illegal_argument_exception Reason: "invalid sequence of tokens near ['for']." CausedBy: "Type: no_viable_alt_exception Reason: "no_viable_alt_exception: null""""
I also tried boolean variable inside loop and try to return that at the end but I get the same error.
I tried simple for loop with counter (i) to check the syntax but same error. So it seems like anything I use inside loop is returning error.
Can someone help to find the correct syntax ? Thanks in advance.
CodePudding user response:
You cannot have a for
loop inside a condition, it doesn't make sense.
Here is how your script should look like:
def hqCoordExist = !doc[params.headquartersCoordinatesField].empty;
def distToHq = doc[params.headquartersCoordinatesField].arcDistance(params.latitude, params.longitude);
if (hqCoordExist && distToHq * 0.000621371 <= params.maxDistance) {
return true;
}
def officesExist = !doc[params.offices].empty;
if (officesExist) {
for (def office : doc[params.offices].values) {
def distToOffice = office.coordinates.arcDistance(params.latitude, params.longitude);
if (distToOffice * 0.000621371 <= params.maxDistance) {
return true;
}
}
}
return false;
CodePudding user response:
This worked for me. I had to check key and size of offices param. :
if(!doc[params.headquartersCoordinatesField].empty && doc[params.headquartersCoordinatesField].arcDistance(params.latitude, params.longitude) * 0.000621371 <= params.maxDistance)
{
return true;
}
def officesCollection = new ArrayList();
if(doc.containsKey(params.offices) && doc[params.offices].size() > 0)
{
officesCollection = doc[params.offices].value;
for (def office : officesCollection)
{
def distToOffice =
office.coordinates.arcDistance(params.latitude, params.longitude);
if (distToOffice * 0.000621371 <= params.maxDistance)
{
return true;
}
}
}
return false;