Query function script score if multiple values in a field

Hi,
I have a question about creating the following query:
My field location can store multiple values in it, e.g.:

"geolocations": [
     "51.2171728, 8.654843",
     "50.2171728, 8.645487",
]

Is it possible to increase or decrease the score?

I want a higher score, if there is only one element in it and a lower score the more elements are in it.

The last hour i spend searching for a solution in the net and documentations but did not found anything.

Maybe using a functions with script_score? Appreciate any help :slight_smile:

Yes, a function_score query with a script score function would work. Something like this:

GET test/_search
{
  "query": {
    "function_score": {
      "query": {
        *** YOUR REGULAR QUERY GOES HERE ***
      },
      "functions": [
        {
          "script_score": {
            "script": "if (doc['geolocations'].values.length > 0) { return 1.0 / (doc['geolocations'].values.length) } else { return 0 }"
          }
        }
      ]
    }
  }
}

You could also add a field to your documents at index time that indicates how many geolocations there are. Then you could use that number in a function_score field value factor function, and you would not have to use scripting.

1 Like

Hi Abdon,
thank you so much for the script :slight_smile:
But i think your 2nd idea is even better :smiley:

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.