Incrementing param value within a script

This is a simplified version of the problem.

         "should": [
        {
          "script_score": {
            "query": {
              "match_all": {}
            },
           "script": {
            "source": """
                    def score = 0;
                    if(params.ct1 < 3) {
                      score = 20;
                      params.ct1++;
                    }
                    return score;
                  """,
            "params": {
              "ct1": 0
            }
          }
          }
        }
      ],

Ideally I'd only get a 20 score 3 times but it's not working consistently - sometimes I get more than 3.
Is this possible? Has anyone done anything similar?

params is intended to be read-only for score scripts as documented here. With a score script there is no way to reliably pass state between multiple documents, and the behavior seen here is a side effect of Java using references for types in general. The reason that you see more than 3 at times is because the params gets reset for each Lucene segment that the query executes against.

1 Like

Thank you for your quick response and I suspected what you said but wasn't 100% sure. Can you think of or is there another way to accomplish the same task? I'm really trying to bucket results even after they've been scored. A "group by" to the scoring - I'm doing this in rescore which I thought would do the trick. Or maybe there's some other feature I could be using.